如何检查输入是否是int型

C++: How to check if input is only an int?

本文关键字:输入 是否是 int 检查 何检查      更新时间:2023-10-16

我是c++的新手,正在尝试创建一个程序,用户可以在其中输入所需项目的整数值。当程序使用int值运行时,当输入像'2.2,1.34a, b5'这样的值时,它不起作用。

到目前为止我的程序如下:

    int main(){
       int nuts, bolts, screws;
       cout << "Number of nuts: ";
       cin >> nuts;
       cout << "nnNumber of bolts: ";
       cin >> bolts;
       cout << "nnNumber of screws: ";
       cin >> screws;
       system("cls");
       cout << "Nuts: " << nuts << endl;
       cout << "Bolts: " << nuts << endl;
       cout << "Screws: " << nuts << endl;
       return 0;
    }

任何帮助都会很感激。由于

当您需要对用户输入执行错误检查时,最好创建一个函数来执行错误检查。

int readInt(std::istream& in)
{
   int number;
   while ( ! (in >> number ))
   {
     // If there was an error, clear the stream.
     in.clear();
     // Ignore everything in rest of the line.
     in.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
   }
   return number;
}

,然后使用:

bolts = readInt(std::cin);

等。

如果您想在用户提供错误输入时退出,您可以使用:

if ( !(cin >> bolts) )
{
    std::cerr << "Bad input.n";
    return EXIT_FAILURE;
}