【发布时间】:2020-08-07 02:27:14
【问题描述】:
我正在尝试制作一个程序,该程序从名为 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;
}
【问题讨论】:
-
"但它不能正常工作。"缺乏信息。文件内容是什么,被看到了,期待什么?一个小例子会有很大帮助。
-
作为一个风格挑剔的人,我反对
pFile——就叫它file,不需要在变量名中编码指针。国际海事组织。 -
刚刚编辑了问题并给出了.txt文件的示例。