我必须在C中编写一个程序来读取包含几行文本的文件,每行包含两个变量:一个数字(%f)和一个字符串:
EX: file.txt
============
24.0 Torino
26.0 Milano
27.2 Milano
26.0 Torino
28.0 Torino
29.4 Milano
Run Code Online (Sandbox Code Playgroud)
有我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[])
{
int r, line = 0, found = 0;
float temp, t_tot = 0;
char loc[32];
FILE *fp;
fp = fopen(argv[1], "r");
if (fp == NULL)
{
printf ("Error opening the file\n\n'");
exit(EXIT_FAILURE);
}
if (argc == 3)
{
r = fscanf(fp, "%f %s\n", &temp, loc);
while (r != EOF)
{
line++;
if (r == 2)
{
if(strcmp(argv[2], loc) == 0)
{
t_tot += temp;
found++;
}
}
else
printf ("Error, line %d in wrong format!\n\n", line);
}
printf ("The average temperature in %s is: %.1f\n\n", argv[2], (t_tot/found);
}
}
Run Code Online (Sandbox Code Playgroud)
该程序需要读取所有行,并找到我写的城市argv[2].比它会告诉我那个城市的平均温度,通知我文件中的一行是否格式错误.
程序正在编译给我,但它没有在屏幕上输出任何东西......我怎么能解决这个问题?fscanf在这种情况下使用是正确的还是更好fgets?
我是学生,所以,请给我一个"学术"的方法来解决它:)
小智 11
有几件事.
首先,你必须使用fclose().
其次,您的代码需要fscan()文件中的每一行.不仅在while()循环之前,而且在每个while循环中你都需要fscan()进行下一次迭代.
第三,你没有计算平均温度,你正在计算所有发现的tempuratures的总和.通过在最后一个printf()中将"t_tot"更改为"(t_tot/found)"来解决此问题.
最后,我不确定为什么你没有得到任何输出.你的输入就像"myprogram file.txt Milano"对吗?适合我.无论如何,这是你的(编辑过的)代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[])
{
int r, line = 0, found = 0;
float temp, t_tot = 0;
char loc[32];
FILE *fp;
fp = fopen(argv[1], "r");
if (fp == NULL)
{
printf ("Error opening the file\n\n'");
exit(EXIT_FAILURE);
} else {
if (argc == 3)
{
r = fscanf(fp, "%f %s\n", &temp, loc);
while (r != EOF)
{
line++;
if (r == 2)
{
if(strcmp(argv[2], loc) == 0)
{
t_tot += temp;
found++;
}
}
else
printf ("Error, line %d in wrong format!\n\n", line);
r = fscanf(fp, "%f %s\n", &temp, loc);
}
printf ("The average temperature in %s is: %.1f\n\n", argv[2], (t_tot / found));
}
fclose(fp);
}
}
Run Code Online (Sandbox Code Playgroud)