std::cin在所有情况下,我认为你不能强制拒绝接受非整数输入.你总是可以写:
std::string s;
std::cin >> s;
Run Code Online (Sandbox Code Playgroud)
因为字符串不关心输入的格式.但是,如果要测试读取整数是否成功,则可以使用以下fail()方法:
int i;
std::cin >> i;
if (std::cin.fail())
{
std::cerr << "Input was not an integer!\n";
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以只测试cin对象本身,这是等效的.
int i;
if (std::cin >> i)
{
// Use the input
}
else
{
std::cerr << "Input was not an integer!\n";
}
Run Code Online (Sandbox Code Playgroud)