c++ - 为什么 std::cin.clear() 在这个简单的程序中不起作用?

标签 c++ iostream

我在做一些练习来打发时间,遇到了一个我不理解的行为,我来解释一下:

练习:

Write a program that reads and stores a series of integers and then computes the sum of the first N integers. First, ask for N, then read the values into a vector, then calculate the sum of the first N values.

因为我要求 N 作为第二步:

在第二个 std::cin (std::cin >> values_to_compute) 中,它必须离开 while 语句才能继续程序,“只有当”读到的不是双重的。例如,我可以打字; 'k' 或“你好吗?”或 Ctrl + Z(我在 Windows 10 上)。

int main() {
    try {
        double holder {0};
        std::vector<double> values;
        while (std::cin >> holder) {
            values.push_back(holder);
        }
        std::cin.clear();
        std::cout << "Out of the loop, now entering to the other std::cin\n";
        int values_to_compute {0};
        std::cin >> values_to_compute;
        std::cout << "Computing...\n";
        double result_computed {0};
        for (int i {0}; i < values_to_compute; ++i) {
            result_computed += values[i];
        }
        std::cout << "Result computed " << result_computed << '\n';

        system("pause");
        return 0;
    }
    catch (std::runtime_error& e) {
        std::cerr << e.what() << '\n';

        system("pause");
        return 1;
    }
}

好吗? 所以... std::cin 使 while 处于 not good() 状态。我必须调用 std::cin.clear() 才能再次使用 std::cin

好的,然后呢? 好吧,如果我键入 Ctrl+Z 退出 while 循环,std::cin.clear() 作品;如果我键入的内容不是 Ctrl + Z,则 std::cin.clear() 不起作用。

我想知道这种行为的原因。

最佳答案

那是因为std::cin::clear清除 cin 的错误状态但它不会从流中删除数据。您可以使用 std::cin::ignore()在阅读之前阅读并丢弃一行文本 values_to_compute .

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

确保#include <limits>得到std::numeric_limits .

关于c++ - 为什么 std::cin.clear() 在这个简单的程序中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54640425/

相关文章:

c++ - Clang C++ 交叉编译器 - 从 Mac OS X 生成 Windows 可执行文件

C++ 链接器错误 iostream 重载

c++ - Visual C++ 不允许 iostream

c++ - 为 C++ ostream 自定义流缓冲区

c++ - 是否可以从 cin 输入 "prepare"?

c++ - 在 C++ 中初始化字符串

c++ - 如何使用模板正确重写这个使用继承的 C++ 代码

c++ - C/C++ 宏中的逗号传递给另一个宏

c# - 如何使用多个异步或缓冲 IO 流?

c++ - 如何让 Code::Blocks 在同一目录中显示 .h 和 .cpp 文件?