【发布时间】:2026-01-13 10:50:01
【问题描述】:
我正在编写一些代码以使用 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.
【问题讨论】:
-
该循环的更简单版本是
while (std::cin >> x) std::cout << x << '\n';。