C ++-其他返回Elseif

Dea*_*uir 1 c++ if-statement

我正在尝试学习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";
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我输入数字,它可以正常工作。但是,如果我输入的不是数字,例如abcd,它会打印You selected 0,但我希望它打印Invalid number

Ste*_*ner 5

如果将atoi无法传递的值传递给该值,例如,传递“ text”时,则返回值为atoiis 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;
} 
Run Code Online (Sandbox Code Playgroud)

输出:

Invalid argument
Run Code Online (Sandbox Code Playgroud)