This question already has an answer here:
- Implement an integer parser 28 answers
You already know that the atoi
function of stdlib.h
converts a string to an integer.
atoi
(copied from here)
int atoi (const char * str);
Convert string to integer
Parses the C-string
str
interpreting its content as an integral number, which is returned as a value of typeint
.
Example
#include <stdio.h> /* printf, fgets */
#include <stdlib.h> /* atoi */
int main ()
{
int i;
char buffer[256];
printf ("Enter a number: ");
fgets (buffer, 256, stdin);
i = atoi (buffer);
printf ("The value entered is %d. Its double is %d.\n",i,i*2);
return 0;
}
Your task is to implement it, making sure it works for all negative integers in the range, and try to make the code as small as you can.