如何从 C 中的 txt 文件中读取和添加数字

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), "[=11=]") == 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;
}

您可以使用strtok拆分每一行的数字,然后使用atoi函数将字符串转换为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;

}

strcmp(fgets(str, MAX_LEN, pFile),"[=10=]") 在很多方面都是错误的。其一,strcmp 的参数必须是字符串(空指针不是),但 fgets returns NULL 出现错误或文件末尾时。您需要检查它没有 return NULL 然后您可以比较 str 中的字符串。但是,不需要 strcmp 反对 "[=17=]"(或者,在这种情况下等效地,"")来检测文件结尾,因为那是 fgets returns NULL.

另一个问题是您同时使用 fscanffgets 阅读 - 选择一个并坚持下去。我推荐 fgets,因为它通常更容易正确(例如,在无效输入时,从 fscanf 中恢复要困难得多,并确保您不会陷入无限循环,同时也不会丢失任何输入)。当然,您需要在 fgets 之后解析 str 中的整数,但是有许多标准函数(例如 strtolatoisscanf).

不要使用 !feof(file) 作为循环条件(例如,参见 Why is “while ( !feof (file) )” always wrong?)。如果您正在阅读 fgets,则在 returns NULL.

时结束循环

您的程序有多个问题:

  • 不测试是否传递了命令行参数。
  • while (!feof(pFile) && !ferror(pFile)) 遍历文件总是错误的:feof() 仅在实际读取尝试后才提供有效信息。只是测试读取是否失败。
  • if fscanf(pFile, "%d", &num) == 1) 添加数字而不是仅仅计算数字。
  • strcmp(fgets(str, MAX_LEN, pFile), "[=14=]") 将在文件末尾失败,当 fgets() returns NULL.

如果文件只包含数字,只需使用 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;
}