Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basics of strtol?

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,?,?);
like image 715
James Thompson Avatar asked Feb 10 '13 02:02

James Thompson


People also ask

How does strtol work?

The strtol() function converts a character string to a long integer value. The parameter nptr points to a sequence of characters that can be interpreted as a numeric value of type long int. The strtoll() function converts a character string to a long long integer value.

What is the base in strtol?

Note that the base argument strtol is set to 16 , which is the base for hexadecimals.

What is the use of strtol function in C?

In the C Programming Language, the strtol function converts a string to a long integer. The strtol function skips all white-space characters at the beginning of the string, converts the subsequent characters as part of the number, and then stops when it encounters the first character that isn't a number.

How do I know if strtol failed?

To determine if 0 is valid, you must also look at the value errno was set do during the call (if it was set). Specifically, if errno != 0 and the value returned by strtol is 0 , then the value returned by strtol is INVALID.


1 Answers

The first argument is the string. It has to be passed in as a C string, so if you have a std::string use .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. strtol can do anything from binary (base 2) to base 36. If you want strtol to pick the base automatically based on prefix, pass in 0.

So, the simplest usage would be

long l = strtol(input.c_str(), NULL, 0);

If you know you are getting decimal numbers:

long l = strtol(input.c_str(), NULL, 10);

strtol returns 0 if there are no convertible characters at the start of the string. If you want to check if strtol succeeded, use the middle argument:

const char *s = input.c_str();
char *t;
long l = strtol(s, &t, 10);
if(s == t) {
    /* strtol failed */
}

If you're using C++11, use stol instead:

long l = stol(input);

Alternately, you can just use a stringstream, which has the advantage of being able to read many items with ease just like cin:

stringstream ss(input);
long l;
ss >> l;
like image 151
nneonneo Avatar answered Oct 22 '22 05:10

nneonneo