【问题标题】:adding using file integers input使用文件整数输入添加
【发布时间】:2014-05-02 06:55:53
【问题描述】:

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

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;
}

【问题讨论】:

  • 很抱歉,我看不到您的问题。你想把哪些值加起来放在哪里?顺便说一句,你只提到了两列,但我看到了三列,所以也许你忘了一列(车号​​?)。
  • 我想将第二列编号和第三列编号相加,但我无法单独获得每个编号。
  • 换句话说,我怎样才能单独抓住每个数字
  • 所以如果我想将 250 + 525 添加到 235,我该怎么做
  • 那么你想把第二列和第三列相加吗?

标签: c file input


【解决方案1】:

这取决于你想做什么。

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

    ...
    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);

【讨论】:

  • 如果这是对您问题的回答,您可以接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-23
  • 2011-06-18
  • 2018-12-03
  • 2012-12-25
  • 2022-11-14
  • 1970-01-01
  • 2017-08-11
相关资源
最近更新 更多