【发布时间】:2014-09-02 11:06:45
【问题描述】:
我正在提示用户输入文件名,但是一旦用户按下回车键,它也会将其带入文件名。所以这个文件永远找不到。
int main (){
char file[100];
FILE *fp;
printf("Please enter a valid filename:\n");
fgets(file,100,stdin);
fp=fopen(file, "r");
if(!fp){
printf("File not found.\n"); \\This will always happen because a new line is added to the user's input.
return 1;}
如果我使用
scanf("%s", file);
该问题没有发生,但我听说 scanf 不是一个好用的函数,并且会引入新问题。 fgets如何解决换行问题?
【问题讨论】:
-
-1 表示“这个问题没有显示任何研究工作”。 Google search for
fgets Introducing new line in user's input site:stackoverflow.com(即此问题的标题)会将该重复项作为第三个结果。