C++ - 否则返回 Elseif
C++ - Else Returning 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
,例如,当您传递"text"时,则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
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何取消对nullptr的屏蔽,返回正确的对象
- 奇怪的结构&GCC&clang(void*返回类型)
- 架构决策:返回std::future还是提供回调
- 从python中调用C++函数并获取返回值
- 矩阵向量乘法(cublasDgemv)返回零
- C++ - 否则返回 Elseif