c++ - C++ - 否则返回 Elseif
问题描述
我正在努力学习 C++。当我尝试做时else
,它并没有按照我的想法工作。
我已经尝试了我能想到的一切。
#include <iostream>
using namespace std;
int main()
{
char name[50];
int text;
int text2;
cout << "Enter 1-2: ";
cin >> name;
string s = name;
text = atoi(s.c_str());
if (text == 1) {
cout << "You selected 1";
}
else if (text == 0) {
cout << "You selected 0";
}
else if (text == 3) {
cout << "You selected 3";
}
else {
cout << "Invalid number";
}
}
如果我输入数字,它可以正常工作。但是,如果我输入的不是数字,例如abcd
,它会打印You selected 0
,但我希望它打印Invalid number
。
解决方案
如果您传递一个atoi
无法转换的值,例如当您传递“文本”时,则返回atoi
值为0
。例如,在 cppreference.com 上提供atoi描述:
返回值成功时str内容对应的整数值。如果转换后的值超出相应返回类型的范围,则返回值未定义。如果无法进行转换,则返回0。
要检查转换错误,您可以使用stol
,它会在转换错误时引发异常:
string invalid_num = "text, i.e. invalid number";
int num=0;
try{
num = (int)stol(invalid_num);
}
catch(const std::invalid_argument){
cerr << "Invalid argument" << "\n";
num = -1;
}
输出:
Invalid argument
推荐阅读
- dhis-2 - DHIS2 API 获取数据集而不是单个数据元素
- java - 无法在android中启动Activity
- postgresql - 无密码用户的 PostgreSQL 本地数据库访问
- cucumber-jvm - Cucumber 版本 - 6.9.1 - 无法在场景大纲“示例”中传递空白字符串
- jsonschema - 是否可以创建有时可以为空而有时不能的模式引用?
- c - 使用宏的函数参数
- vba - 从 SAP 到 Excel 的小数分隔符问题:“1,056”与“1.056”(因子 1000)
- node.js - 节点快递)我遇到了这个问题
- apache-spark - 来自多列的 Pyspark 日期格式
- javascript - 如何在 Chrome 控制台中访问 Javascript 对象