简体   繁体   English

将char数组转换为一个int

[英]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.. 我不能使用atoi,需要逐位进行处理。如何将其保存为int类型。给定一个char * temp将其全部合并为一个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. 但是,请考虑到您的数量很大,因此对于ilong long int类型更合适。

#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 . 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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