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