Reputation: 103
I am trying to learn C++. When I try to do else
, it isn't working how I think it should.
I have tried everything I can think of.
#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";
}
}
If I enter numbers, it works correctly. However, if I enter something that isn't a number, e.g. abcd
, it prints You selected 0
, but I want it to print Invalid number
.
Upvotes: 1
Views: 84
Reputation: 35154
If you pass a value to atoi
that cannot be converted, e.g. when you pass "text", then the return value of atoi
is 0
. Confer, for example, atoi description on 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.
To check conversion errors, you could use stol
, which throws an exception on conversion errors:
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;
}
Output:
Invalid argument
Upvotes: 5