Cin.clear() issue

Cin.clear() issue

本文关键字:issue clear Cin      更新时间:2023-10-16

我正在编写一个应该只接受整数的程序,我目前正在使用

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)。

你会在这个网站上找到成百上千的关于这个主题的变体。