C++:如何检查输入是否只是一个 int?

标签 c++ c int

我是 C++ 新手,正在尝试创建一个程序,用户在其中输入所需项目数量的整数值。虽然程序使用 int 值运行,但当输入“2.2, 1.34a, b5”等值时,它不起作用。

这是到目前为止我的程序:

    int main(){
       int nuts, bolts, screws;

       cout << "Number of nuts: ";
       cin >> nuts;

       cout << "\n\nNumber of bolts: ";
       cin >> bolts;

       cout << "\n\nNumber 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;
}

关于C++:如何检查输入是否只是一个 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32557687/

相关文章:

c++ - C89 或 C++03 是否定义了严格的别名规则?

c - 如何初始化 GActionMap 变量?

python - 调用函数时“int”对象不可调用

c++ - 如何解决方法重载中的函数调用?

c++ - POCO C++ 对象到 JSON 字符串序列化

c - 如何将 linux 应用程序设置为操作系统中可用的 "global"?

C: 2D-Array 没有从一开始就打印出来

ios - 清除 xCode 中静态 Int 的未使用实体警告

Java hashcode逆向计算

c++ - 交叉编译SFML时对libpng相关符号的 undefined reference