#include #include #include int main(void) { int nDay, nMonth, nYear; // The numbers, as integers string sDay, sMonth, sYear; // The numbers, as strings string sDate = "01/02/1999"; // The source string // Break the string up in to chunks. // // string.substr() extracts a substring from the main string. The // first parameter is where in the string to start (the first // character is at position 0). The second parameter is how many // characters to extract. sDay = sDate.substr(0, 2); sMonth = sDate.substr(3, 2); sYear = sDate.substr(6, 4); // Convert the substrings in to numbers using atoi(). atoi() // handles C style strings, which can be retrieved using the // string.c_str() method. nDay = atoi(sDay.c_str()); nMonth = atoi(sMonth.c_str()); nYear = atoi(sYear.c_str()); // This could be done without the temporary variables by doing this: // // nDay = atoi(sDate.substr(0, 2).c_str()); // nMonth = atoi(sDate.substr(3, 2).c_str()); // nYear = atoi(sYear.substr(6, 4).c_str()); // // instead. // Output the results as numbers. Note that the leading zeroes have // disappeared. cout << "Day: " << nDay << " " << "Month: " << nMonth << " " << " Year: " << nYear << "\n"; // Output the substrings. Note that the leading zeroes are here. cout << "Day: " << sDay << " " << "Month: " << sMonth << " " << "Year: " << sYear << "\n"; }