user788171
user788171

Reputation: 17553

C++ atoi() only returns the first digit

I am experiencing a strange problem with atoi()

I am doing a conversion like this:

cout<<atoi(mystring.c_str())<<endl;

mystring is a string with something like 3245524

The above code would only return 3 to the stdout.

Now, if I make the string smaller, e.g. less than 1000000, then I get the entire number returned to stdout.

Any ideas what is causing this problem? This is still well below the limit of C++ int so it is not some overflow.

EDIT, some additional information. When I simplify the command to simply:

cout<<mystring.c_str()<<endl;

The stdout is something like 3.24552e+06

Is the problem related to this?

Upvotes: 0

Views: 439

Answers (1)

Martin J.
Martin J.

Reputation: 5118

From your edit:
The contents of mystring are "3.24552e+06" , i.e. a scientific (floating-point) string representation for the number 3245520.
Therefore, atoi parses the first integer it finds in mystring, as expected, which is: 3.
If mystring contained "3245520", your atoi call would return the integer 3245520.

Upvotes: 1

Related Questions