0

Hi guys I'm not really understanding how I would separate the users inputs when using getline(). For example the user inputs his birth date and from that I extract the month, date, and year from that.

eg.) for Sunday, January 2, 2010. I have

int main()
{
    string inputStream;
    string date, month, day, year;
    string i;
    string j;
    getline(cin, inputStream);
    //cin >> date >> month >> day >> year;
    i = inputStream.substr(0, inputStream.find(","));
    j = inputStream.substr(inputStream.find(","), inputStream.find(","));
    date = i;
    month = j;
    cout << month << " " << day <<  " was a " << date << " in" << year << endl;
    return0;
}

For i it works properly and will display sunday but for j it doesn't seem to want to work. Can someone show me where I went wrong? I'm not sure how I would extract the next value after the date.

1 Answers1

0

Following modifications are done in your code to parse the day, date, month and year from the input string (as per your input format) successfully.

#include <iostream>
using namespace std;

int main()
{
    string inputStream;
    string date, month, day, year;
    string i;
    string j;
    getline(cin, inputStream);

    // day
    day = inputStream.substr(0, inputStream.find(","));
    // month
    int pos1 = inputStream.find(",") + 2; // Go ahead by 2 to ignore ',' and ' ' (space)
    int pos2 = inputStream.find(" ", pos1); // Find position of ' ' occurring after pos1
    month = inputStream.substr(pos1, pos2-pos1); // length to copy = pos2-pos1
    // date
    int pos3 = inputStream.find(",", pos2); // Find position of ',' occurring after pos2
    date = inputStream.substr(pos2, pos3-pos2); // length to copy = pos3-pos2
    // year
    year = inputStream.substr(pos3+2); // Go ahead by 2 to ignore ',' and ' ' (space)

    cout << "day = " << day << endl;
    cout << "date = " << date << endl;
    cout << "month = " << month << endl;
    cout << "year = " << year << endl;

    return 0;
}

Hope this helps you.

cm161
  • 492
  • 3
  • 6
  • Wow thank you so much, you explained so much to me. Thank you for helping me understand how find worked. – I. Quach Oct 14 '15 at 02:42