具有两个cin的无限循环
Infinite loop with two cin
我有一个函数,我想在其中读取整数,直到输入非整数。我想重复这个功能,直到我按下回车键。但角色被传递到第二个cin,它变成了一个无限循环。
void read () {
int x;
while ( cin >> x );
}
int main () {
char a;
do {
read ();
cin.ignore (256, 'n')
cin >> a;
} while ( a != 'n' )
}
1)您忘记删除std::cin
中的失败位;使用clear()
2) 为了检测空输入,我建议使用std::string
和std::getline()
我建议像
#include <iostream>
#include <string>
void read () {
int x;
while ( std::cin >> x ) ;
std::cin.clear();
std::cin.ignore(std::numeric_limits<int>::max(), 'n');
}
int main () {
std::string b;
do {
read();
std::getline(std::cin, b);
} while ( false == b.empty() );
return 0;
}
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 为什么我的两个 cin 语句没有在程序结束时运行?
- Cin 需要两个输入
- 两个 cin / cout 语句合并为一个
- 当我使用 cin 进行两个输入时,如何接受一个输入
- 两个输入C++来自 Bash 的 cin
- 当其中一个字符串来自cin时,无法比较两个字符串.这里怎么了
- 使用cin.ignore()跳过两个空间
- 在C 中使用两个GetLine(CIN,S)
- CIN为什么将浮动值分为两个部分
- 具有两个cin的无限循环
- 连续两个"cin"不起作用
- while 循环不能有两个 CIN 语句吗?
- 如何在c++中使用两个cin语句
- 从cin读取两个字符串并将其写回时出现意外行为
- 辛:等<ENTER>着。两个继续 cin.忽略不起作用