首页 > 解决方案 > 你如何编码,如果 x 不等于数字,程序将退出

问题描述

我对此感到困惑。例如

#include <iostream>
int main(){
    using namespace std;
    int x, y;
    cout << "enter a number: \n";
    cin >> x
    if (x != ){                             // If user inputs anything besides a number, Program will then exit
    cout << "invalid";
    }
  return 0;
  }

我可以使用什么代码,如果用户决定输入字母而不是数字,程序将输出无效,然后程序将退出

标签: c++

解决方案


>>与 结合使用的运算符cin返回一个引用,可以检查该引用以查看将条目分配给整数 x 的任务是否成功。如果操作失败,意味着条目不是整数,则返回空指针。在这种情况下,!(cin >> x)评估为true

#include <iostream>
#include <cstdlib> // for exit()
using namespace std;
int main(){     
  int x;
  cout << "enter a number: \n";
  if (!(cin >> x) ){// If user inputs anything besides a number, Program will then exit
    cout << "invalid entry.\n";
    exit(0);
  }
  cout << "you entered number: " << x << endl;
  return 0;
}

另请参阅,例如,此问题的答案以获取更多信息。

编辑:

作为等效的替代方案,也可以使用cin.fail(). 这导致代码更易于阅读:

cout << "enter a number: \n";
cin >> x ;
if (cin.fail()){
 ...
}

推荐阅读