所以我得到了我的程序的整个设置,我能够读取整个文件内容。我唯一需要的是能够添加每一列并将其放入我所做的变量中。第一列是英里秒是加仑。那么我怎样才能使用我的代码。
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;
}
答案 0 :(得分: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);