你可以读取一个字符串,从中提取一个整数,然后确保没有任何东西:
std::string line; std::cin >> line; std::istringstream s(line); int x; if (!(s >> x)) { // Error, not a number } char c; if (s >> c) { // Error, there was something past the number }