Monday, November 7, 2011

String manipulations

For lab 12, you need to request a date from the user, in the format "mm-dd-yyyy". This is a string but you will need to parse it into its component integers. This is how you go about doing that.

You'll need to include the string header file first.

#include <string>

Request the date from the user.

string dateString;
cout << "Enter date using the format mm-dd-yyyy: ";
cin >> dateString;


Now, you parse the string. To get your hands on the year, you need the last four characters.

int year = atoi(dateString.substr(6, 4).c_str());

The substr function returns four characters, starting with the 7th position in the calling string. You use the c_str function to make the string a c-style string (just go with me on this one). The atoi converts the string to an integer.

For the month, you start at the beginning of the dateString and grab just the first two characters, like so;

int month = atoi(dateString.substr(0, 2).c_str());

The substr function starts at the beginning of the string, position 0, and sends back a string of two characters.

Now, all you need are the two pesky characters in the middle which represent the day of the month:

int day = atoi(dateString.substr(3, 2).c_str());