【问题标题】:Problems with getline() function? [duplicate]getline() 函数有问题吗? [复制]
【发布时间】:2014-01-06 14:45:02
【问题描述】:

下面代码中的getline 函数有问题。在“获取”信息部分,我希望能够存储一个完整的句子,但我不能让它工作。

当我打开我的程序时,它只是跳过信息的输入。

ps:我是 C++ 新手

这是我遇到问题的代码部分(输入信息):

void add() {
    string name;
    string faction;
    string classe;
    string race;
    string info;

    ofstream wowdatabase("wowdatabase.txt", ios::app);
    cout << "Add a race or class" << endl;
    cout << "---------------------------------------------------------" << endl;
    cout << "" << endl;
    cout << "Enter the name of the race or class (only small letters!):" << endl;
    cin >> name;

    cout << "Enter Race (Type -, if writen in name section):" << endl;
    cin >> race;

    cout << "Enter Class (Type -, if writen in name section):" << endl;
    cin >> classe;

    cout << "Enter faction (Alliance/Horde):" << endl;
    cin >> faction;

    cout << "Enter the information:" << endl;
    getline(cin, info);

    wowdatabase << name << ' ' << faction << ' ' << classe << ' ' << race << ' ' << info << endl;
    wowdatabase.close();
    system("CLS");
    main();
}

现在它工作正常 =) 但是,当我想再次输出信息时,它只显示句子中的第一个单词?

【问题讨论】:

标签: c++


【解决方案1】:

在此声明之前

getline(cin, info);

拨打以下电话

cin.ignore( numeric_limits<streamsize>::max(), '\n' );

要使用此调用,您必须包含标头 &lt;limits&gt;

问题是执行语句后

cin >> faction;

对应于输入键 ENTER 的换行符在输入缓冲区中,下一次 getline 调用读取该字符。

【讨论】:

    【解决方案2】:

    读取分数后,会留下一个空行字符。随后对getline 的调用将读取它。为了避免这种情况,在getline 调用之前添加对cin.ignore 的调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-16
      • 1970-01-01
      • 1970-01-01
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      • 2016-12-02
      • 1970-01-01
      相关资源
      最近更新 更多