c++ - 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.
解决方案
您的输入中没有任何内容会导致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;
}
推荐阅读
- javascript - Facebook 登录 API 出现问题
- selenium - 在 Junit5 中启用并行执行时 Selenium 测试的屏幕截图
- typescript - 从函数数组创建返回类型的元组类型,以便我们可以使用该元组类型转换 `map` 的结果
- powershell - 获取共享中所有文件夹的 ACL
- testing - 处理命令时发生未知的服务器端错误。原始错误:您必须包含 platformName 功能?
- xml - 如何将 Postgres SQL 语句导出为 XML 转储
- python - 如何使用 SymPy 加速长函数的符号导数?
- unit-testing - Lagom 服务测试
- android - 从 SupportFragmentManager 获取我的片段之一时出现问题
- node.js - 从 TypeScript 中的依赖项访问类型声明