K
Kay
Is it possible to convert char * to integer ?
if yes, how to do it ?
if yes, how to do it ?
Kay said:Is it possible to convert char * to integer ?
if yes, how to do it ?
Kay said:Is it possible to convert char * to integer ?
if yes, how to do it ?
Kay said:Is it possible to convert char * to integer ?
if yes, how to do it ?
Phlip said:char const * z = "12";
stringstream stream = z;
int q = 0;
if (z >> q)
cout << "yes" << endl;
(strtol() also works.)
Method said:Isn't using 'atoi' function in <stdlib.h> much simpler?
Method Man said:Isn't using 'atoi' function in <stdlib.h> much simpler?
Method said:Isn't using 'atoi' function in <stdlib.h> much simpler?
Mike Wahler said:Yes, but it cannot be used safely. (Does not protect from
overflow, which would cause undefined behavior. Also, a
valid result of zero cannot be distinguished from an error,
which 'atoi()' indicates by returning zero.
-Mike
Method Man said:Hmm, I would just write my own version of 'atoi' then. At the least, it's
good practice for a C/C++ job interview.
Kay said:Is it possible to convert char * to integer ?
if yes, how to do it ?
Mike Wahler said:Why would you not use 'strto(u)l()'?
If a candidate wasted time reinventing what the standard library
already has, I would not be impressed. I'd be more impressed with
one who knows which tools are available, and when/how/where to apply
them.
Anyone familiar with C or C++ will recognize 'strtol()' at a glance,
whereas upon encountering a 'home-grown' conversion function, one
would need to find out what the darn thing actually does. Also, a
standard library function has a far better chance of being fully
debugged and robust.
-Mike
Method said:I guess I've always used 'atoi'. This is what I was taught back in my 1st
year university CS class for converting any C-style strings to int.
Regarding the interview question. I've actually been asked to specifically
implement 'atoi' in two separate interviews. I suppose the context was
simply that it's a good test for one's pointer knowledge and error handling
ability with strings.
Karl Heinz Buchegger said:int atoi( char* String )
{
int Result;
sscanf( "%d", Result );
return Result;
}
Method said:Hmm, I would just write my own version of 'atoi' then. At the least,
it's good practice for a C/C++ job interview.
Phlip said:If asked to write atoi() at a job interview, I would match its exact ISO
specification, verbally point out all its minor flaws,
reveal when and when not I would use it, and write wrapper code that
defends its calls.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.