c++ - getline(cin, var) 问题。程序忽略命令

标签 c++

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

最佳答案

我觉得你需要使用 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>> 将跳过前导空格,即按 std::ctype 分类.您可以在测试程序中看到,通过使用 unsetf(std::ios_base::skipws) 关闭此行为,它将提取空白。通过使用 cin.ignore,您可以简单地丢弃它,因为它不需要。有关详细信息,请参阅 cin and getline skipping input .

关于c++ - getline(cin, var) 问题。程序忽略命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26311132/

相关文章:

c++ - 如何在 wxperl EVT_BUTTON 中传递附加参数

c++ - 用非虚函数覆盖虚函数

c++ - 如何在非托管 ATL GUI 中嵌入 Windows 窗体?

C++ ifstream 失败,为什么这条线没有到达它应该去的地方?

C++ shared_ptr 和内置指针

c++ - 在 C++ 中创建对象

c++ - 握手失败,出现 fatal error SSL_ERROR_SSL : error:100000f7:SSL routines:OPENSSL_internal:WRONG_VERSION_NUMBER

c++ - 嵌套 if 的性能问题

c++ - 我需要一个具有多个值的键。你会推荐什么数据结构?

c++ - Linux:fork & execv,等待子进程挂起