明天我有一个测试,文件让我很困惑。我写的这段代码停在fscanf(f1,"%d",& n);并没有接受任何输入。我在编码时遵循了老师的例子。有没有人知道为什么会这样?还有F2是完全必要的吗?教师的练习题是说要打开文件阅读,阅读所有内容,保持所有工资的总和,然后一旦阅读完成,提示输出文件名字符串,打开它,然后写入所有收入的平均值。我理解fprintf和fscanf的程度,以及读写模式的区别,但是,我不明白为什么F2是必要的?他在使用不同变量名的类似示例中使用F2。提前谢谢。
#include <stdio.h>
int main(){
FILE *f1;
FILE *f2;
char name[30];
char name2[30];
float wage;
float wage_total;
int n;
int SSN;
printf("What is the file name?\n");
scanf("%s", name);
f1 = fopen(name, "r");
printf("What is the file name for F2?\n");
scanf("%s", name2);
f2 = fopen(name2,"w");
int i;
wage = 0;
fscanf(f1, "%d", &n);
for(i = 0; i < n; i++){
fscanf(f1,"%d", &SSN);
fscanf(f1, "%f", &wage);
wage_total += wage;
}
fprintf(f2,"%f", wage_total);
fclose(f1);
fclose(f2);
system("pause");
return 0;
}
教师的例子:
#include <stdio.h>
int main() {
FILE* fp1;
FILE* fp2;
int n;
int i;
int id,len,width;char word[30],word2[30];
printf("type input fname:");
scanf("%s",word);
printf("type output fname:");
scanf("%s",word2);
fp1 = fopen(word, "r");
fp2 = fopen(word2,"w");
fscanf(fp1,"%d", &n);
for(i=0;i<n;i++)
{ fscanf(fp1,"%d%d%d", &id, &len, &width);
if ( (len*width) > 500)
printf("%d %d %d", id, len, width);
}
fclose(fp1);
fclose(fp2);
system("pause"); return 0;
}