Re: [C++] Reading an int from char[]

From: Chris \( Val \) (chrisval_at_bigpond.com.au)
Date: 02/25/04


Date: Wed, 25 Feb 2004 23:27:07 +1100


"Stefan Buhr" <stefan.buhr@post.rwth-aachen.de> wrote in message
news:c1i3lu$it2$1@nets3.rz.RWTH-Aachen.DE...
| "Chris ( Val )" <chrisval@bigpond.com.au> schrieb:
| > | I want to read an integer value from char *argv[].
| > |
| > | When I assign int var = *argv[1] and call my program with the parameter
| 85,
| > | the variable var gets the value 57. Who can tell me what to do?
| >
| > # include <cstdlib>
| > int Number = std::strtol( argv[1], 0, 10 );
| >
| > Check out the documentation for 'std::strtol', and find
| > out how you can use the second parameter to check for
| > errors.
|
| Thank you very much for your fast answer.
| Finally, I tried atoi from cstdlib, which actually seems to work.

Yes, 'std::atoi' will also work, but it does not provide
you with the error checking you really need, and that is
why 'std::strtol' is preferred over 'std::atoi'.

Additionally, C++ offers 'std::istringstream' from <sstream>
for this kind of task, and is also an excellent choice, although
it can take a little bit of code to employ error checking.

It is a good idea for you to understand both methods, and if you
have any further questions, please ask.

Cheers.
Chris Val



Relevant Pages


Loading