c - 使用文件整数输入进行添加

标签 c file input

所以我得到了程序的完整设置,并且能够读取整个文件内容。我唯一需要的就是能够添加每一列并将其放入我创建的变量中。第一列是英里,第二列是加仑。那么我怎样才能使用我的代码使其成为可能。

54 250 19

62 525 38

71 123 6

85 1322 86

97 235 14

#include <stdio.h>
#include <conio.h>

int main()
{
    // pointer file
    FILE *pFile;
    char line[128];
    int miles;
    int gallons;
    int mpg;

    // opening name of file with mode
    pFile = fopen("Carpgm.txt","r");

    //headers
    printf("Car No.  Miles Driven    Gallons Used\n");
    //checking if file is real and got right path
    if (pFile != NULL)
    {

        while (fgets(line, sizeof(line), pFile) != NULL)
        {
            int a, b, c;

            if (sscanf(line, "%d %d %d", &a, &b, &c) == 3)
            {
                /* Values read */
                printf("%d        %d             %d\n",a, b, c);


            }


        }
        mpg = miles / gallons;
        printf("Total miles driven: \n",miles);
        printf("Total Gallons of gas: \n",gallons);
        printf("Average MPG: \n",mpg);

        printf("%d",a);

        //closing file
        fclose(pFile);        
    }
    else 
    {
        printf("Could not open file\n");     

    }

    getch();
    return 0;
}

最佳答案

这取决于你想做什么。

如果您只想添加值,您可以执行以下操作:

    ...
    int miles = 0;
    int gallons = 0;
    ...
    /* Values read */
    miles += b;
    gallons += c;
    ...

请注意,您无法像关闭文件之前那样打印 a,因为 a 仅在 while 循环中定义。 此外,您的 printf 语句将无法按预期工作,您忘记指定格式 %d,请执行:

    printf("Total miles driven: %d\n",miles);
    printf("Total Gallons of gas: %d\n",gallons);
    printf("Average MPG: %d\n",mpg);

关于c - 使用文件整数输入进行添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23422479/

相关文章:

c - 如何从c中的动态数组中访问数据?

c - c中的malloc链表

ruby - Rake - 仅复制更改的文件

javascript - 文档未检测输入值

validation - 一种基于Result <_,E1>和Result <T,E2>来获取Result <T,E>的好方法吗?

c++ - .txt 到 vector<struct> 故障

c - 为什么我不能返回这个数组?

c - 具有与 MIT Kerberos 兼容的远程构建功能的 IDE

c - 从文件读取时获取结构中的垃圾值

javascript - WinJS加载本地json文件