Cin.clear() issue
Cin.clear() issue
我正在编写一个应该只接受整数的程序,我目前正在使用
int x;
cin >> x;
while(cin.fail()){
cout << "error, please enter an integer" << endl;
cin.clear();
cin.ignore();
cin >> z;
cout << "you entered" << z << endl;
}
然而,如果我输入一个双精度,例如1.2,程序会忽略小数点,但会将z值设置为2,并且不会请求用户输入。我能做些什么来阻止这种情况?
在这一切失去控制之前,这里再次是一个典型的输入操作示例:
#include <string> // for std::getline
#include <iostream> // for std::cin
#include <sstream> // for std::istringstream
for (std::string line; std::cout << "Please enter an integer:" &&
std::getline(std::cin, line); )
{
int n;
std::istringstream iss(line);
if (!(iss >> n >> std::ws) || iss.get() != EOF)
{
std::cout << "Sorry, that did not make sense. Try again.n";
}
else
{
std::cout << "Thank you. You said " << n << ".n";
}
}
它会一直要求您输入整数,直到您关闭输入流或以其他方式终止它(例如,键入Ctrl-D)。
你会在这个网站上找到成百上千的关于这个主题的变体。
相关文章:
- Seg Fault Issue C++ (file IO / getline)
- 如果 std::vector::clear() 不是静态的,如何在没有实例的情况下调用它?
- Issue with WriteProcessMemory
- std::partition segfault issue
- VSCode C/C++ Intellisense issue: Undefined identifiers (Linu
- OpenGL glBufferSubData Offset issue
- 在 STL 容器的 STL 容器上调用 clear
- boost::property_tree XML issue
- 了解 cin.fail() 和 cin.clear语言 - Vector 追加程序
- 在 c++ 中,发生故障后是否需要 stream.clear()?
- 为什么不能通过在错误输入后设置 std::cin.clear() 来使用 std::cin?
- qt QWidget::closeEvent link issue
- QT 和 JIRA Rest API: /rest/api/2/issue/createmeta 意外返回韩语的 iss
- Crypto++ GetModulus() issue
- cin.clear()是否保留EOF
- C++向量:clear() 和 resize() 之间的区别
- Vector.push_back Issue
- std::vector::clear()ing 二维向量线程的内部向量安全吗?
- QPointer::clear() 是删除其引用的指针,还是"Clears this QPointer object."其他含义?
- Cin.clear() issue