c++ - 在 C++ 中使用 cin 时使用循环计数被忽略

标签 c++ input cin

我设置了一个 for 循环,根据用于此深度优先搜索算法的邻接列表的节点数,接收用户输入 X 次。

int nodeNum;

cout << "Number of nodes?: " << endl;
cin >> nodeNum;

cout << "Names: " << endl;
for (int i = 0; i < nodeNum; i++)
{
    getline(cin, tempName);

    v.push_back(tempName); //pushing the name of node into a vector
}

当我将其提交到我所在大学和 GCC 的在线编译器时,它会跳过最后的输入。示例 - 我输入数字 8,它只需要 7 个节点。我怎样才能解决这个问题?

最佳答案

声明cin >> nodeNum读取整数,但在整数之后,但在换行符之前,立即保留文件指针。

因此循环的第一次迭代读取该换行符作为第一行。您可以通过以下方式看到此效果:

#include <iostream>
using namespace std;

int main(void) {
    int nodeNum;
    string tempName;

    cout << "Number of nodes?\n";
    cin >> nodeNum;

    cout << "Names:\n";
    for (int i = 0; i < nodeNum; i++)
    {
        getline(cin, tempName);
        cout << "[" << tempName << "]\n";
    }

    return 0;
}

sample 运行:

Number of nodes?
2xx
Names:
[xx]
aaa
[aaa]

一种解决方法是放置:

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

紧接在 cin >> nodeNum 之后- 这会清除当前行末尾的字符。您需要包括 <limits>头文件来使用它。

将更改应用于上面的示例代码:

#include <iostream>
#include <limits>
using namespace std;

int main(void) {
    int nodeNum;
    string tempName;

    cout << "Number of nodes?\n";
    cin >> nodeNum;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    cout << "Names:\n";
    for (int i = 0; i < nodeNum; i++)
    {
        getline(cin, tempName);
        cout << "[" << tempName << "]\n";
    }

    return 0;
}

显着改善情况:

Number of nodes?
2xx
Names:
aaa
[aaa]
bbb
[bbb]

关于c++ - 在 C++ 中使用 cin 时使用循环计数被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29600405/

相关文章:

c++ - 重载 >> 读取分数

c++ - 通过通用引用传递静态 constexpr 变量?

python - 多种可能的输入

c++ - OpenCV - 禁用打印异常

javascript - 输入事件监听器(onkeypress、onkeydown)在 Android 数字键盘中不起作用

python-3.x - 如何解决 python 中 input() 的问题?

c++ - 输入 cin C++ 没有任何内容

c++ - 如何在 C++ 中的字符串之间使用 cin?

c++ - 如何让 MATLAB 的 system() 或 dos() 实时显示控制台输出?

c++ - 在 64 位 Ubuntu (18.04) 系统上运行 32 位可执行文件时,如何修复 ld-linux.so.2 中 gdb 中的挂起问题?