I am really confused. I have to be missing something rather simple but nothing I am reading about strtol() is making sense. Can someone spell it out for me in a really basic way, as well as give an example for how I might get something like the following to work?
string input = getUserInput;
int numberinput = strtol(input,?,?);
The first argument is the string. It has to be passed in as a C string, so if you have a
std::stringuse.c_str()first.The second argument is optional, and specifies a
char *to store a pointer to the character after the end of the number. This is useful when converting a string containing several integers, but if you don’t need it, just set this argument to NULL.The third argument is the radix (base) to convert.
strtolcan do anything from binary (base 2) to base 36. If you wantstrtolto pick the base automatically based on prefix, pass in 0.So, the simplest usage would be
If you know you are getting decimal numbers:
strtolreturns 0 if there are no convertible characters at the start of the string. If you want to check ifstrtolsucceeded, use the middle argument:If you’re using C++11, use
stolinstead:Alternately, you can just use a
stringstream, which has the advantage of being able to read many items with ease just likecin: