使用getline()然后从用户输入中提取字符串(使用C ++)

时间:2015-10-13 04:17:32

标签: c++ getline c-strings

大家好我不太了解在使用getline()时如何分隔用户输入。例如,用户输入他的出生日期,然后从中提取月份,日期和年份。

例如。)2010年1月2日星期日。我有

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;
}

对于我来说它运作正常并且会显示星期天但是对于j它似乎并不想工作。有人能告诉我哪里出错了吗?我不确定如何在日期之后提取下一个值。

1 个答案:

答案 0 :(得分:0)

在您的代码中进行了以下修改,以便成功地从输入字符串(根据您的输入格式)解析日期,日期,月份和年份。

#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;
}

希望这会对你有所帮助。