我想我已经尝试过任何东西(刷新标准输入、scanf 以使用换行符等),但没有任何效果像我希望的那样。出于某种原因,第 3 次 scanf 在以下代码中修改了第 2 次 scanf 中的变量:
#include <stdio.h>
int main()
{
char first_name[16], last_name[21];
char filename[11];
FILE *opening;
printf("The program saves your first and last name into a file.\n");
printf("Enter your first name:");
scanf("%s", first_name);
getchar();
printf("Enter your last name:");
scanf(" %s", last_name);
getchar();
printf("File where you want to save your name:");
scanf(" %s", filename);
opening = fopen(filename, "wb");
fprintf(opening, "%s %s", first_name, last_name);
printf("\nSuccessfully saved the data!");
fclose(opening);
return 0;
}
输出:
The program saves your first and last name into a file.
Enter your first name: John
Enter your last name: Doe
File where you want to save your name: filename.txt
Successfully saved the data!
一切都很好,除了 filename.txt 的内容是这样的:
约翰吨
我猜't'字符不知何故来自'txt',但我刚刚开始学习C,我不知道如何修复这段代码才能工作。请问各位高手能帮帮我吗?