gpt4 book ai didi

C++ - 否则返回 Elseif

转载 作者:行者123 更新时间:2023-11-30 01:02:11 28 4
gpt4 key购买 nike

我正在努力学习 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。商议,例如,atoi cppreference.com 上的描述:

Return value Integer value corresponding to the contents of str on success. If the converted value falls out of range of corresponding return type, the return value is undefined. If no conversion can be performed, ​0​ is returned.

要检查转换错误,您可以使用 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

关于C++ - 否则返回 Elseif,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56642633/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com