At 2/1/14 11:48 AM, coln wrote:
Actually you know what, I was thinking: doesn't atoi always return, whether or not &line[0] is a valid number?
atoi returns 0 on fail, so the loop would be useless.
You're right, I didn't think about that little problem. One solution to allow the user to give a 0 would be to include an extra parameter in the if statement that simply checks the value of the C-string:
#include <iostream>
#include <string>
#include <stdlib.h>
int main() {
int num;
std::string line;
while (true) {
getline(std::cin, line);
if ((num=atoi(&line[0])) || (line[0] == '0' && line[1] == '\0')) {
break;
}
}
}
Which isn't very elegant, and I don't recommend doing that. Another, and better, solution that I should of thought of in the first place would be to use the strtol function instead:
#include <iostream>
#include <string>
#include <stdlib.h>
int main() {
long num;
std::string line;
while (true) {
getline(std::cin, line);
char* end;
long temp = strtol(line.c_str(), &end, 10);
if (!*end) {
num = temp;
break;
}
}
}
You don't need to use a temporary variable, but strtol() returns 0 upon an error, so if it receives bad input you'll be assigning 0 to your variable. If that won't cause erroneous behaviour in your application then you can get rid of the temporary.
Basically that works by setting the end pointer to the first place it finds an error (i.e. non-digit character), which will end up being a non-zero value. If no error is found then end pointer points to a '\0' character, which is just 0. The 10 being passed as the third argument means the value will be treated as base10. You could set that to 16 if you wanted to accept hexadecimal, for example, which would deem "0xF45AE" as valid input.
That will work better, and will also be faster than using stringstreams. It's also worth nothing that iostreams in C++ are not localisation friendly, not that you're likely to run into that being a problem if you're just converting integers. I know many C++ programmers that recommend never using iostreams for that very reason.