C++ 中的输入检查问题

Problems with input check in c++

本文关键字:检查 问题 输入 C++      更新时间:2023-10-16

我希望程序循环直到输入有效(x 是 int,x>0),但是当我给它 1,1 时,我的程序接受输入,当我给它一个字符串时无限循环,重复"错误的输入!

#include <iostream>
using namespace std;
int main()
{
    bool fail;
    int x;
    do{
        cin >> x;
        fail=(cin.fail() || x<=0);
        if (fail){
            cout << "Wrong input!" <<endl;
            cin.clear();
        };
    }while(fail);
    return 0;
}

在 if 语句中使用标准成员函数ignore。例如

std::cin.ignore(std::numeric_limits<std::streamsize>::max(),’n’);

或者只是

std::cin.ignore();

它用于跳过缓冲区中的无效符号。

您可以读取整行并使用字符串流转换该行:

#include <iostream>
#include <sstream>
int main()
{
    bool fail;
    int x;
    do{
        std::string line;
        fail = ! getline(std::cin, line);
        if( ! fail) {
            std::istringstream s(line);
            fail = ! (s >> x) 
                || x < 0  
                || ! s.eof(); // The entire line represents an integer
        }
        if(fail) {
            std::cout << "Wrong input!" << std::endl;
        };
    } while(fail);
    return 0;
}