【问题标题】:getline(cin, var) issue. Program ignores the commandgetline(cin, var) 问题。程序忽略命令
【发布时间】:2014-12-06 07:33:01
【问题描述】:

我对第 23 行的代码有疑问。(请参阅下面的代码)

当我使用 "cin >> studentNum";我没有问题,程序读取一个字符串作为名字,但是如果我想使用 "getline(cin, studentNum)" 收集更多数据来读取更多字符串和全名一样,程序只是跳过命令并询问分数。

这是为什么呢?

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int studentNum, testNum, i, j;
    double sum, testScore, average;
    string studentName;
    i = 0;

    // asking user for input

    cout << "Please enter the number of students in this classroom: " << endl;
    cin >> studentNum;

    cout << "Now enter the number of tests each student has taken in this class: " << endl;
    cin >> testNum;
    while (i < studentNum)
    {
        cout << endl << "Now please enter the firstname of the student: " << endl;
        cin >> studentName; //**My Problem is in this line ###########**
        j = 0;
        sum = 0;
        while (j < testNum)
        {
            cout << "Please enter the score of each test, then hit enter: " << endl;
            cin >> testScore;
            sum += testScore;
            j++;
        }
    i++;
    }
}

【问题讨论】:

    标签: c++


    【解决方案1】:

    你应该清除状态标志并刷新 steram

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

    【讨论】:

    • @remyabel,你说得对。我忘了包括头文件
    【解决方案2】:

    听起来你需要使用cin.ignore。您需要丢弃流中仍然存在的换行符。

    #include <limits>
    // This is not a C++11 feature, works fine in C++98/03
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::getline(std::cin, studentName);
    

    默认情况下,operator&gt;&gt; 将跳过前导空格,即由std::ctype 分类。您可以通过使用unsetf(std::ios_base::skipws) 关闭此行为,在测试程序中看到它会提取空格。通过使用cin.ignore,您可以简单地丢弃它,因为它是不可取的。如需更多信息,请参阅cin and getline skipping input

    【讨论】:

      猜你喜欢
      • 2011-11-26
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      • 2020-03-14
      • 2014-06-22
      • 2013-09-23
      • 2018-09-18
      • 1970-01-01
      相关资源
      最近更新 更多