0

Why doesn't this work?

printf("%d \n\n\n\n", atoi("11110010100"));

it outputs -1774891788... I just want it outputted as it is. It seems to work just fine if the number is a bit smaller.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
something
  • 517
  • 3
  • 10
  • 22

2 Answers2

4

atoi returns an int. You pass a string which contains a number bigger than what int(in your implementation) can hold. So, you have an integer overflow.

To print the maximum value an int can hold, include limits.h and print INT_MAX.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
1

int atoi (const char * str) convert string to integer,and the basic signed integer type capable of containing at least the [−32767,+32767] range,

the 11110010100 is bigger than integer storage capability, so you have an overflow.

you can try this method to parse a String to a Double: atof
http://www.lemoda.net/c/string-to-double/

Yacino
  • 645
  • 2
  • 10
  • 32
  • 3
    It would be exceptional to find a system using a two byte integer type these days. – David Hoelzer May 09 '15 at 12:00
  • No, kamel is right: according to K&R, **2.2 Data Types and Size**, "ints are *at least* 16 bits" (see also http://stackoverflow.com/a/11438985/2564301). And `atoi` returns an `int`. – Jongware May 09 '15 at 13:49