簡體   English   中英

將char數組轉換為一個int

[英]converting char array into 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");

}

像這樣:

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

但是,請考慮到您的數量很大,因此對於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;    
}

它應該工作,這是一個演示


編輯 :這是一個優化的溶膠:

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

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM