简体   繁体   中英

converting char array into one int

I can't use atoi, need to do it digit by digit.. How do I save it in a int.. given a char* temp put it all in one int..

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
int main () {

    char* temp = "798654564654564654";
    int i = 0;

    for (i = 0; i < strlen(temp); i++) {

        printf("%d", temp[i] - 48);

    }

    printf("\n");

}

Like this:

int i = 0, j = 0;
while (temp[j])
    i = i*10 + temp[j++] - '0';

However, take to account that your number is very big, so for i the long long int type is more appropriate.

#include<string.h>

int main() {    
   char* s = "798654564654564654";
   unsigned long long num = 0;    
   int i = 0, j = strlen(s);      
   for(i=0; i< j && s[i]>='0' && s[i]<='9'; i++)     
       num = num * 10 + s[i] - '0';    
   printf("%lld",num);    
   return 0;    
}

It should work, Here is a demo .


EDIT : Here is an optimized sol :

unsigned long long latoi(char * s) {
   unsigned long long num = 0;
   while(*s>='0' && *s<='9') num = num * 10 + *(s++) - '0';
   return num;
}

And the demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM