[英]Why does my C program only read 1 printf function?
我的 C 编译器上没有错误显示,但我不明白为什么程序不会读取 printf 函数,该函数将运行“为 ___ 输入一个标记”以便我可以输入数据。这发生了,所以我无法加载 .lst 文件或 .txt 文件。
#include <stdlib.h>
int main(void){
FILE *fin, *fout;//fin+fout are file pointers/handlers
char name[100];
float mark;
fin = fopen("saved.lst", "r");//open in read mode as an ascii file
if (fin == NULL)
{
printf("file can't be opened for reading\n");
return -1;
}
fout = fopen("updated.txt", "w");
if (fin == NULL)
{
printf("file can't be opened for reading\n");
return -1;
}
while (fscanf (fin, "%s",&name) == 1)
{
printf("Enter a mark for %s: ", name);
scanf ("%f", &mark);
fprintf(fout, "%s: %f",name, mark ); //formats & displays the data
//close the file
fclose(fout);}
return 0;
}
我编译并修复了错误。 根据评论: fclose(fout) 应该在 while 循环下面,fin 也应该在那里关闭。 在 fscanf 中 &name 应该只是名称。 在 fprintf 中,您可能希望在行尾输出一个 \\n。 (我在saved.lst 的新行中使用几个名称运行它,并检查是否在updated.txt 中添加了一个标记)。
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
FILE *fin, *fout; // fin + fout are file pointers/handlers
char name[100];
float mark;
fin = fopen("saved.lst", "r"); // open in read mode as an ascii file
if (fin == NULL)
{
printf("file fin can't be opened for reading\n");
return -1;
}
fout = fopen("updated.txt", "w");
if (fout == NULL)
{
printf("file fout can't be opened for writing\n");
return -1;
}
while (fscanf (fin, "%s", name) == 1)
{
printf("Enter a mark for %s: ", name);
scanf ("%f", &mark);
fprintf(fout, "%s: %f\n", name, mark); //formats & displays the data
}
// close the files
fclose(fin);
fclose(fout);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.