c++ - 你如何编码,如果 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 的任务是否成功。如果操作失败,意味着条目不是整数,则返回空指针。在这种情况下,!(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()){
...
}
推荐阅读
- css - 如何将 2 个按钮彼此相邻居中
- java - 我的任务是创建一个 Java 应用程序,该应用程序使用 2 个同步线程来计算每月利息并更新帐户余额
- c++ - msgpack:在不知道类型的情况下解压自定义类
- php - 在 SQL 中将字符串从 PHP 转换为 int
- c - 在C中通过http发送图像
- c++ - 下一个排列定义
- spring-cloud-stream - 用于多租户服务的 Spring Cloud Stream
- python - 获取函数的源文件行号
- angular - 什么是 ViewChild
- ruby-on-rails - 如何猴子补丁 ActiveRecord::QueryMethods?