c++ - 用 while(cin >> x) 填充 std::vector<int> 的问题

标签 c++ parsing io while-loop cin

所以我有一个学校项目需要我等待用户输入 Ctrl + Z 来结束循环。老师说最好的方法是检查 cin >> x,如果这是真的,那么他们还没有输入 Ctrl + Z。好吧,经过一些测试和来回,我无法弄清楚问题出在哪里,所以我制作了一个 super 简单的代码版本,看看是否可以修复它。什么都没有真正改变。无论如何,这是简单的代码:

#include "Proj_02.h";

vector<int> dog;
string entry = "";
int value = 0;

void main()
{
    Menu();
}

void Menu()
{
    do
    {
        //Ask the user to enter a number
        cout << "Enter a number: ";
        //Save the number to a vector
        do
        {
            cout << "k";
            getline(cin, entry);
            value = atoi(entry.c_str());
        }while(value == 0);

        while (cin >> value)
        {
            cout << "L";
            dog.push_back(value);
        }

    //when the user presses Ctrl + Z stop asking
    }while(cin >> entry);

    //Display all of the numbers
    for(int i = 0;i < dog.size();i++)
    {
        cout << dog.at(i) << endl;
    }

    system("PAUSE");
}

所以当它运行时会发生什么是代码等待我再输入 2 个值,然后甚至在完成任何输入之后再做任何事情。我的猜测是它与引起某种缓冲区干扰的 while cin >> entry 有关,但我对如何解决这个问题没有任何可靠的想法。如果有人能提供帮助,那就太好了。

最佳答案

使用流时,请在使用结果之前测试状态。

因此:

while(std::cin >> value) {
    ...
}

if(std::getline(cin, entry)) {
    ...
}

关于c++ - 用 while(cin >> x) 填充 std::vector<int> 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18671401/

相关文章:

c++ - 将项目小部件宽度(列表内容)调整为父 QListWidget 宽度

c++ - 在 Ubuntu Linux 中使用 Nvidia 卡的 OpenCL 出现 -1001 错误

xml - xbrl us gaap contextRef 标准?

python - 当 .close() 失败时,Python 3 中的文件描述符会发生什么情况?

Python IOError : File not open for writing and global name 'w' is not defined 错误

c++ - 强制初始化单例类

php - 解析 html 页面

database - 使用未知的数据库文件?

ruby - ruby 的 StringIO 类到底是什么?

c++ - CUDA:使用 tex2D() 的问题