【问题标题】:using getline() and then extracting strings from user input (using C++)使用 getline() 然后从用户输入中提取字符串(使用 C++)
【发布时间】:2015-10-13 04:17:32
【问题描述】:

大家好,我不太了解在使用 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;
}

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

【问题讨论】:

  • 对于j,您的子字符串在同一点开始和结束,因此为空。查看您传递给substr 的参数。

标签: c++ getline c-strings


【解决方案1】:

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

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

希望对你有所帮助。

【讨论】:

  • 哇,非常感谢,你向我解释了这么多。感谢您帮助我了解 find 的工作原理。
猜你喜欢
  • 1970-01-01
  • 2012-08-24
  • 2017-03-31
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 2017-12-28
  • 1970-01-01
相关资源
最近更新 更多