检查用户的输入是否为确定类型 (C++)

  • 本文关键字:类型 C++ 是否 用户 c++
  • 更新时间 :
  • 英文 :


我正在编写一个程序,从用户那里获得一个数字并打印出来,我想检查用户的输入是否是一个数字。

#include <iostream>
int main(){
int x;
std::cout << "Enter a number: ";
std:;cin >> x;
/*
Here's what I want to do
if (isInteger(x)){
std::cout << "nYour number is " << x << ;
} else if (isNotInteger()){
std::cout << "nInvalid valuenn";
}
*/
return(0);
}

如果operator>>读取值失败,则将流的错误状态设置为failbit。您可以测试这种情况,例如:

if (std::cin >> x) {
std::cout << "nYour number is " << x << ;
} else {
std::cout << "nInvalid valuenn";
}

如果你想继续阅读关于失败的信息,你必须首先调用流的clear()方法来重置错误状态,并且还从缓冲区中读取/删除无效数据,例如流的ignore()方法,例如:

if (std::cin >> x) {
std::cout << "nYour number is " << x << ;
} else {
std::cout << "nInvalid valuenn";
std::cin.clear();
std::cin.ignore(std::numeric_liimits<std::streamsize>::max(), 'n');
}

最新更新