[英]How to Read and Add Numbers from txt file in C
我正在嘗試制作一個程序,該程序從名為numbers.txt的文本文件中讀取數字,該文件在每行中包含不同的數字。
例如:
8321
12
423
0
...
我創建了這個程序,但它不能正常工作。 我嘗試了很多東西,不知道該怎么做。 有人可以指導我正確的方向嗎? 謝謝!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 1000
int main(int argc, char *argv[]) {
char str[MAX_LEN];
FILE *pFile = fopen(argv[1], "r");
int num;
int sum = 0;
int count = 0;
if (pFile == NULL) {
printf("Error opening file.\n");
return 1;
}
while (!feof(pFile) && !ferror(pFile)) {
if (fscanf(pFile, "%d", &num) == 1) {
count++;
while (strcmp(fgets(str, MAX_LEN, pFile), "\0") == 0) {
printf("%s", str);
//sum = sum + (int)(fgets(str, MAX_LEN, pFile));
printf("\n");
}
}
}
fclose(pFile);
printf("count = %d \n", count);
printf("sum = %d \n", sum);
return 0;
}
strcmp(fgets(str, MAX_LEN, pFile),"\0")
在很多方面都是錯誤的。 一方面, strcmp
的參數必須是一個字符串(null 指針不是),但fgets
在錯誤或文件結束時返回NULL
。 您需要檢查它是否沒有返回NULL
然后您可以比較str
中的字符串。 但是,不需要針對"\0"
(或者,在這種情況下等效地為""
)使用strcmp
來檢測文件的結尾,因為那是fgets
返回NULL
的時候。
另一個問題是您同時使用fscanf
和fgets
閱讀 - 選擇一個並堅持使用它。 我推薦使用fgets
,因為它通常更容易正確處理(例如,在無效輸入時,從fscanf
中恢復要困難得多,並確保您不會陷入無限循環,同時也不會丟失任何輸入)。 當然,您需要在fgets
之后從str
解析 integer,但是有許多標准函數(例如strtol
、 atoi
、 sscanf
)。
不要使用!feof(file)
作為循環條件(參見,例如, 為什么“while (?feof (file) )”總是錯誤的? )。 如果您正在使用fgets
閱讀,請在返回NULL
時結束循環。
您可以使用strtok
拆分每行中的數字,然后使用atoi
function 將 string 轉換為int
。
例如:
while(fgets(str, MAX_LEN, pFile)) {
// if the numbers are separated by space character
char *token = strtok(str, " ");
while(token != NULL) {
sum += atoi(token);
strtok(NULL, " ");
}
}
如果每行只有一個數字,則不需要使用strtok
:
while(fgets(str, MAX_LEN, pFile)) {
sum += atoi(str);
// OR
sscanf(str,"%d\n", &new_number)
sum += new_number;
}
您的程序有多個問題:
while (!feof(pFile) && !ferror(pFile))
遍歷文件總是錯誤的: feof()
僅在實際讀取嘗試后才提供有效信息。 只需測試讀取是否失敗。fscanf(pFile, "%d", &num) == 1)
添加數字而不是僅僅計算數字。fgets()
返回NULL
時strcmp(fgets(str, MAX_LEN, pFile), "\0")
將在文件末尾失敗。 如果文件只包含數字,只需使用fscanf()
讀取這些數字並在您瀏覽文件時添加它們。
這是修改后的版本:
#include <stdio.h>
int main(int argc, char *argv[]) {
FILE *pFile;
int num
int sum = 0;
int count = 0;
if (argc < 2) {
printf("Missing filename\n");
return 1;
}
if ((pFile = fopen(argv[1], "r")) == NULL) {
printf("Error opening file %s\n", argv[1]);
return 1;
}
while (fscanf(pFile, "%d", &num) == 1) {
sum += num;
count++;
}
fclose(pFile);
printf("count = %d \n", count);
printf("sum = %d \n", sum);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.