【发布时间】:2021-03-02 22:03:25
【问题描述】:
代码是:
#include <stdio.h>
#include <string.h>
int main (void)
{
char ch,str[100],sen[100];
printf("enter the string : ");
fgets(str,sizeof(str),stdin);
printf("enter the character : ");
scanf("%c",&ch);
printf("enter the sentence : ");
fgets(sen,sizeof(sen),stdin);
printf("character is : %c\n",ch);
printf("string is : %s\n",str);
printf("sentence is : %s",sen);
return 0;
}
这就是我希望我的程序工作的方式: 输入:
enter the string : abcde
enter the character : k
enter the sentence : i am a beginner.
输出:
character is : k
string is : abcde
sentence is : i am a beginner.
这就是它的结果:
enter the string : abcde
enter the character : k
enter the sentence : character is : k
string is : abcde
sentence is :
这个程序没有提示用户输入句子。
请告诉我为什么这个fgets() 函数不能正常工作。
【问题讨论】:
-
fgets()仅用于阅读内容。因此它不会提示任何事情。 -
scanf("%c",&ch);只读取一个字符。如果输入换行符,它将在缓冲区中留下换行符,并且换行符将被fgets()消耗掉。 -
在 scanf 之后调用 getchar() 以消耗缓冲区中剩余的换行符。