C 程序在要求用户输入时跳过一行
C program skips a line when asking for user input
printf("Number of tracks: ");
fflush( stdin );
scanf("%d", &track);
printf("Is this an album or single: ");
fflush( stdin );
scanf("%c", &type);
当我输入曲目数 5 时,程序会显示 Is this an album or single 并在那里结束程序而不让我输入专辑类型?
点 1
不要用fflush( stdin );
,是undefined behaviour.
相关:来自 C11
标准 docmunet,第 7.21.5.2 章,(强调我的)
int fflush(FILE *stream);
If stream
points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.
要点 2 (完成 应该 由 fflush(stdin)
完成的工作)
改变
scanf("%c", &type);
至
scanf(" %c", &type);
^
|
前导空格忽略缓冲区中类似空格的字符并从 stdin
.
中读取第一个非空格字符
printf("Number of tracks: ");
fflush( stdin );
scanf("%d", &track);
printf("Is this an album or single: ");
fflush( stdin );
scanf("%c", &type);
当我输入曲目数 5 时,程序会显示 Is this an album or single 并在那里结束程序而不让我输入专辑类型?
点 1
不要用fflush( stdin );
,是undefined behaviour.
相关:来自 C11
标准 docmunet,第 7.21.5.2 章,(强调我的)
int fflush(FILE *stream);
If
stream
points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.
要点 2 (完成 应该 由 fflush(stdin)
完成的工作)
改变
scanf("%c", &type);
至
scanf(" %c", &type);
^
|
前导空格忽略缓冲区中类似空格的字符并从 stdin
.