我想打開一個文件中有很多行數字,然後將它從一個字符串轉換爲一個整數。如何將字符串轉換爲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;
}
現在它的返回是不存在的文本文件編號。
任何幫助,將不勝感激!謝謝!
'#包括/*所需的atoi。 * /'< - 爲什麼你會嘗試重新發明輪子?另外:'ctype.h'也會出問題,或者你很樂意使用'isdigit'? –