简体   繁体   English

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

[英]How to Read and Add Numbers from txt file in C

I am trying to make a program that reads numbers from a text file named numbers.txt that contains different numbers in each line.我正在尝试制作一个程序,该程序从名为numbers.txt的文本文件中读取数字,该文件在每行中包含不同的数字。

For example:例如:

8321
12
423
0
...

I have created this program, but it does not work properly.我创建了这个程序,但它不能正常工作。 I have tried many things and don't know what to do.我尝试了很多东西,不知道该怎么做。 Can someone guide me in the right direction?有人可以指导我正确的方向吗? Thank you!谢谢!

#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") is wrong in many ways. strcmp(fgets(str, MAX_LEN, pFile),"\0")在很多方面都是错误的。 For one, the argument of strcmp must be a string (which a null pointer isn't), but fgets returns NULL on error or end of file.一方面, strcmp的参数必须是一个字符串(null 指针不是),但fgets在错误或文件结束时返回NULL You need to check that it didn't return NULL and then you can compare the string in str .您需要检查它是否没有返回NULL然后您可以比较str中的字符串。 However, there is no need to strcmp against "\0" (or, in this case equivalently, "" ) to detect the end of file, because that's when fgets returns NULL .但是,不需要针对"\0" (或者,在这种情况下等效地为"" )使用strcmp来检测文件的结尾,因为那是fgets返回NULL的时候。

Another issue is that you are reading with both fscanf and fgets – pick one and stick with it.另一个问题是您同时使用fscanffgets阅读 - 选择一个并坚持使用它。 I recommend fgets since it's generally easier to get right (eg, on invalid input it's a lot harder to recover from fscanf and make sure you don't get stuck in an infinite loop while also not losing any input).我推荐使用fgets ,因为它通常更容易正确处理(例如,在无效输入时,从fscanf中恢复要困难得多,并确保您不会陷入无限循环,同时也不会丢失任何输入)。 Of course you need to parse the integer from str after fgets , though, but there are many standard functions for that (eg, strtol , atoi , sscanf ).当然,您需要在fgets之后从str解析 integer,但是有许多标准函数(例如strtolatoisscanf )。

Don't use !feof(file) as the loop condition (see, eg, Why is “while (?feof (file) )” always wrong? ).不要使用!feof(file)作为循环条件(参见,例如, 为什么“while (?feof (file) )”总是错误的? )。 If you are reading with fgets , end the loop when it returns NULL .如果您正在使用fgets阅读,请在返回NULL时结束循环。

You can use strtok to split the numbers in each line, then using atoi function to convert string to int .您可以使用strtok拆分每行中的数字,然后使用atoi function 将 string 转换为int

For example:例如:

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, " ");
   }
}

if there is only one number per line, you do not need to use strtok :如果每行只有一个数字,则不需要使用strtok

while(fgets(str, MAX_LEN, pFile)) { 
    sum += atoi(str);
    // OR
    sscanf(str,"%d\n", &new_number)
    sum += new_number;

}

Your program has multiple problems:您的程序有多个问题:

  • no test if a command line argument was passed.不测试是否通过了命令行参数。
  • while (!feof(pFile) && !ferror(pFile)) is always wrong to iterate through the file: feof() gives valid information only after a actual read attempt. while (!feof(pFile) && !ferror(pFile))遍历文件总是错误的: feof()仅在实际读取尝试后才提供有效信息。 Just test if the read failed.只需测试读取是否失败。
  • if fscanf(pFile, "%d", &num) == 1) add the number instead of just counting the numbers. if fscanf(pFile, "%d", &num) == 1)添加数字而不是仅仅计算数字。
  • strcmp(fgets(str, MAX_LEN, pFile), "\0") will fail at the end of the file, when fgets() returns NULL .fgets()返回NULLstrcmp(fgets(str, MAX_LEN, pFile), "\0")将在文件末尾失败。

If the file only contains numbers, just read these numbers with fscanf() and add them as you progress through the file.如果文件只包含数字,只需使用fscanf()读取这些数字并在您浏览文件时添加它们。

Here is a modified version:这是修改后的版本:

#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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM