相关疑难解决方法(0)

如何检查输入是否是一个没有任何其他字符的有效整数?

#include <iostream>
#include <limits>

using namespace std;

int main()
{
    int x;
    cout << "5 + 4 = ";
    while(!(cin >> x)){
        cout << "Error, please try again." << endl;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
    if (x == (5 + 4)){
        cout << "Correct!" << endl;
    }
    else{
        cout << "Wrong!" << endl;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如何检查用户是否输入了有效整数?在我上面写的这个程序中,如果用户输入9,它应该是正确的,但是,如果用户输入9a例如,它应该返回错误,但它不是出于某种原因.我该如何纠正?

我怎么用cin.peek()做的

#include <iostream>
#include <limits>
#include <stdio.h>

using namespace std;

int main()
{
    int x;
    bool ok;
    cout << …
Run Code Online (Sandbox Code Playgroud)

c++ validation integer

5
推荐指数
1
解决办法
2万
查看次数

标签 统计

c++ ×1

integer ×1

validation ×1