我正在编写一些代码以使用cpp从终端读取,但是由于某种原因,它在数字用完后崩溃了。从我在线阅读的内容中,我应该可以使用std::cin检查std::cin.fail()是否成功,但是之前崩溃了。
我正在运行的代码是

#include <iostream>

int main()
{
    int x{};

    while (true)
    {
        std::cin >> x;
        if (!std::cin)
        {
            std::cout << "breaking" << '\n';
            break;
        }
        std::cout << x << '\n';
    }
    return 0;
}
输入:
test@test:~/learn_cpp/ex05$ ./test
1 2
1
2
^C
我最终不得不从程序中按Ctrl + C。版本信息:
gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

最佳答案

输入中的任何内容都不会导致cin设置失败位。因此,while (true)将继续前进。您可以输入一个字母,或其他不是int的东西,这将设置失败位并导致循环中断。
请注意,为此将忽略新行。
如果您知道所有输入都在一行中,则可以使用std::getline读取整行,然后使用std::stringstream从该行读取整数。

#include <iostream>
#include <sstream>
#include <string>

int main() {
    int x{};
    std::string buff;
    std::getline( std::cin, buff );
    std::stringstream ss( buff );
    while ( ss >> x ) {
        std::cout << x << '\n';
    }

    return 0;
}

关于c++ - std::cin.fail()问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62852882/

10-11 22:56
查看更多