c++ - Basics of strtol? -



c++ - Basics of strtol? -

i confused. have missing rather simple nil reading strtol() making sense. can spell out me in basic way, give illustration how might next work?

string input = getuserinput; int numberinput = strtol(input,?,?);

the first argument string. has passed in c string, if have std::string utilize .c_str() first.

the sec argument optional, , specifies char * store pointer character after end of number. useful when converting string containing several integers, if don't need it, set argument null.

the 3rd argument radix (base) convert. strtol can binary (base 2) base of operations 36. if want strtol pick base of operations automatically based on prefix, pass in 0.

so, simplest usage be

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

if know getting decimal numbers:

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

strtol returns 0 if there no convertible characters @ start of string. if want check if strtol succeeded, utilize 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, utilize stol instead:

long l = stol(input);

alternately, can utilize stringstream, has advantage of beingness able read many items ease cin:

stringstream ss(input); long l; ss >> l;

c++ string int strtol

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -