2016-10-10 62 views
0

我想打開一個文件中有很多行數字,然後將它從一個字符串轉換爲一個整數。如何將字符串轉換爲C中的int而不使用庫函數?

我想這樣做,而不使用任何庫函數,所以沒有atoi,沒有strtol也沒有strtoul。

這是我的代碼如下所示:

#include <stdio.h> 
#include <stdlib.h> /* required for atoi. */ 
int main(void) { 
    int i, len; 
    int result=0; 
    double numbers; 
    char num[20]; /* declares a char array. */ 

FILE *file; /* declare a file pointer. */ 
file = fopen("test22.txt", "r"); /* opens the text file for reading only, not writing. */ 

while(fgets(num, 100, file)!=NULL) {  /* this while loop makes it so that it will continue looping until the value is null, which is the very end. */ 
    len=strlen(num); 
    for(i=0; i<len; i++) { 
     result = result*10 + (num[i] - '0'); 
    } 
    printf("%d\n", result); 
    } 
fclose(file); /* closes the file */ 
return 0; 
} 

現在它的返回是不存在的文本文件編號。

任何幫助,將不勝感激!謝謝!

+1

'#包括/*所需的atoi。 * /'< - 爲什麼你會嘗試重新發明輪子?另外:'ctype.h'也會出問題,或者你很樂意使用'isdigit'? –

回答

0

您不會將result重置爲每個新行的零,因此它不斷積累。更改

while(fgets(num, 100, file)!=NULL) { 
    len=strlen(num); 
    for(i=0; i<len; i++) { 
     result = result*10 + (num[i] - '0'); 
    } 
    printf("%d\n", result); 
    } 

while(fgets(num, 100, file)!=NULL) { 
    result = 0; 
    len=strlen(num); 
    // account for newline - should really be smarter than this. 
    // I'll leave that as an exercise for the reader... ;) 
    for(i=0; i< (len - 1); i++) { 
     result = result*10 + (num[i] - '0'); 
    } 
    printf("%d\n", result); 
    } 
+0

嗨安德魯,謝謝你的回答。它仍然打印不在文本文件中的數字。 –

+1

@ N.Vaz文本文件的內容是什麼?發佈的代碼根本不檢查輸入數據是什麼,所以如果文件中的字符不是數字或換行符,它將輸出錯誤的值。另外,如果這些數字太大而無法放入'int',則會出現問題。 –

+0

這只是隨機生成並存儲在其中的數字。請參閱:http://puu.sh/rEhMO/4fa9e11f35.png –

0

功能fgets保留newline在字符串的結尾(如果存在的話),你正試圖爲一個數字轉換。我建議像這樣的循環:

for(i=0; i<len && isdigit(num[i]); i++) 

,你也必須在每次循環之前有

result = 0; 
for(i=0; i<len && isdigit(num[i]); i++) 

請注意,您不能只減少strlen的結果,因爲該文件的最後一行可能末尾沒有newline

編輯:由於您發佈了一個負數的文件,下面是一個將轉換它們的示例。

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

int getnum(char *str) 
{ 
    int result = 0; 
    int neg = 0; 
    if(*str == '-') { 
     neg = 1; 
     str++; 
    } 
    while(isdigit(*str)) { 
     result = result * 10 + *str - '0'; 
     str++; 
    } 
    if(neg) { 
     return -result; 
    } 
    return result; 

} 

int main(void) 
{ 
    printf("%d\n", getnum("123456789\n")); 
    printf("%d\n", getnum("-987654321\n")); 
    return 0; 
} 

程序輸出:

123456789 
-987654321 
+0

嗨天氣風向標,謝謝你的迴應。我編輯了代碼,它實際上給我然後在文本文件中的數字。然而,它們不是按順序的,它返回0,我想這是因爲負數。請參閱:http://puu.sh/rEiqM/24311788c2.jpg –

+0

請參閱更新。 –

+0

注意:轉角情況:'getnum()'可能會或可能不會與字符串版本的'INT_MIN'一起使用。可能不是OP的問題。 – chux