我有以下代码,可以检查输入是否为整数;但是,如果仍然输入诸如“ 5o”之类的内容,则有人可以帮助我确保输入到x的所有数字都是正确的,谢谢!
#include <iostream>
using namespace std;
int main() {
cout << "enter x please: ";
int x;
cin >> x;
while (cin.fail()) {
cout << "sorry wrong input, try again: ";
cin.clear();
cin.ignore();
cin >> x;
}
cout << "correct input!";
return 0;
}
以字符串形式一次读取整行并验证:
#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cctype>
int main()
{
std::printf("Enter x: ");
std::string line;
while (true)
{
if (!std::getline(std::cin, line))
{
std::puts("Stream failed."); // Not much we can do
return -1;
}
if (std::all_of(line.cbegin(), line.cend(), std::isdigit))
break;
else
std::printf("Input is not a number. Try again: ");
}
int const x = std::stoi(line);
std::printf("x = %d\n", x);
}