繁体   English   中英

std::cin.fail() 的问题

[英]Problems with std::cin.fail()

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

我正在运行的代码是

#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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM