Convert string to integer - C String

C examples for String:String Function

Description

Convert string to integer

Demo Code

#include <stdio.h>
#include <ctype.h>

int atoi(char s[]) {
   int i, n, sign;

   for (i = 0; isspace(s[i]); i++)  /* skip white space */
      ;//from  ww  w.  ja  v  a2s . c om
   sign = (s[i] == '-') ? -1 : 1;
   if (s[i] == '+' || s[i] == '-')  /* skip sign */
      i++;
   for (n = 0; isdigit(s[i]); i++)
      n = 10 * n + (s[i] - '0');
   return sign * n;
}

int main() {
   char buf[100];
   int n1, n2;

   printf("string to integer:");
   while (fgets(buf, sizeof buf, stdin) != NULL) {
      sscanf(buf, "%d", &n1);
      n2 = atoi(buf);
      if (n1 != n2)
         printf("error %d %d\n", n1, n2);
   }
   return 0;
}

Result


Related Tutorials