我正在尝试编写一个程序,从文本文件中读取字符和 float ,然后将这些值保存到变量中。 文本文件的格式如下:
S 15.24
G 28.00
S 56.90
H 90.00
0
我试图读取字符,然后让它通过一个开关运行,根据浮点之前的字符进行一些计算(所有 S 值都分组在一起,所有 G 值都分组在一起,等等)
为了让它遍历所有可用的行,我使用了一个 while 循环,当读取的字符到达列表末尾的 0 时,该循环终止。
仅出于测试目的,我让程序在退出循环时打印“完成”。但是,当我运行该程序时,它会运行每个字符并将其正确打印到终端,直到打印 0 之前的值。一旦到达 0,程序不会执行任何其他操作,但不会打印“完成” “就像我想象的那样。
这是我正在使用的代码:
int main()
{
int s_num,g_num,h_num,S,H,G,n_total;
float amount,s_total,s_sum,g_sum,h_sum;
char char_name;
FILE*Input;
Input = fopen("Input.txt","r");
FILE*Output;
Output = fopen("Output.txt","w+");
char_name = 1; //Just using 1 as a way to make the while loop occure
while(char_name != '0')
{
fscanf(Input,"%c%f",&char_name,&amount);
switch(char_name)
{
case 'S':
printf("S,%f\n",amount);
break;
case 'G':
printf("G,%f\n",amount);
break;
case 'H':
printf("H,%f\n",amount);
break;
}
}
printf("done");
return 0;
}
(忽略未使用的值,这些值将在实际程序中使用)
当循环达到 0 时,我需要进行哪些更改才能终止循环?
最佳答案
以下代码:
fscanf(Input,"%c%f",&char_name,&amount);
在到达文件中的最后一个数据行时将无法读取 float 。不需要 switch 语句。使用 if 语句检查第一个字符是否为“0”,然后中断或读取 float 并打印字符和数字。
while (TRUE)
{
fscanf(Input,"%c",&char_name);
if (char_name == '0')
break;
fscanf(Input,"%f",&amount);
printf("%c,%f\n",char_name,amount);
}
关于c - 当 fscanf 从文本文件读取特定值时结束循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28891939/