首页 > 解决方案 > std::cin.fail() 的问题

问题描述

我正在编写一些代码以使用 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.

标签: c++iostreamcin

解决方案


您的输入中没有任何内容会导致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;
}

推荐阅读