0

I am trying to call atoi() on the following strings: "54" and "54df4". While the first input gave me the correct result of 54, the call on second string also gave me the result of 54. I assume that the function is converting the string to decimal as far as possible; instead, it should not convert at all. Why is this so? The following is my code:

cout << "Wrong: " << atoi("54df4") << endl;

Thanks,Rakesh.

Rakesh K
  • 8,237
  • 18
  • 51
  • 64
  • 3
    What makes you think it should behave any differently? – JasonD Mar 06 '13 at 13:36
  • Thank you all for the pointers - I am just curious as to why it is defined to work partially. It shouldn't process such mixed strings right? – Rakesh K Mar 06 '13 at 13:42

4 Answers4

4

That's how atoi is specified to work. If you don't want to convert strings containing non-digit characters you have to pre-scan the string, or use a function such as strtol which can give back the location of the first non-digit character:

cons char *number = "54df4";
char *endp = NULL;

int value = strtol(number, &endp, 10);

if (endp != NULL && endp < (number + strlen(number)))
{
    printf("Stopped scanning in middle of string, it contains non-digit characters\n");
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

From the documentation of atoi

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

UmNyobe
  • 22,539
  • 9
  • 61
  • 90
1

Because that's how atoi is defined. Taking this man page for instance:

The atoi() function converts the initial portion of the string pointed to by nptr to int.

Or in C standard:

C11 (n1570), § 7.22.1.2 The atoi, atol, and atoll functions

The atoi, atol, and atoll functions convert the initial portion of the string pointed to by nptr to int, long int, and long long int representation, respectively.

  • If you want to do complexer operations on the string to convert, use strtol instead (see this answer for instance).
  • If you don't agree with these specifications, write your own function!
Community
  • 1
  • 1
md5
  • 23,373
  • 3
  • 44
  • 93
1

From the following somewhat arbitrarily found man page for atoi....

http://linux.die.net/man/3/atoi

*The atoi() function converts the initial portion of the string pointed to by nptr to int. *

In short, the function is working exactly as it is defined.

David W
  • 10,062
  • 34
  • 60