你怎么编码,如果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;
}

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

运算符>>cin结合使用,返回一个引用,可以检查该引用以查看将条目分配给整数 x 的任务是否成功。如果操作失败,这意味着该条目不是整数,则返回 null 指针。在这种情况下,!(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()){
...
}

最新更新