Reputation: 7319
I'm doing a problem on HR and cant figure out how to check for error without using conditional statements. How is this done in C++?
// if string is int output it, else output "Bad string"
// need to do this without any loops/conditionals
int main(){
string S;
char *end;
long x;
cin >> S;
const char *cstr = S.c_str();
x = strtol(cstr,&end,10);
if (*end == '\0')
cout << x;
else
cout << "Bad string";
return 0;
}
Should I be using something besides strtol?
Upvotes: 1
Views: 483
Reputation: 38919
stoi
is indeed what you'll want to use.
Given an input in string S
one possible way to handle it would be:
try {
cout << stoi(S) << " is a number\n";
} catch(const invalid_argument& /*e*/) {
cout << S << " is not a number\n";
}
The violation here is that stoi
is only required to cosume the leading numeric part of the string
not ensure that the entire string is an int
. So "t3st" will fail cause it's not led by a number, but "7est" will succeed returning a 7. There are a handful of ways to ensure that the entire string
is consumed, but they all require an if
-check.
Upvotes: 1
Reputation: 141554
One way would be:
char const *m[2] = { "Bad string", S.c_str() };
cout << m[*end == '\0'];
Upvotes: 0