问题
#include <stdio.h>
int main()
{
char name[10];
for(int i=0;i<=10;i++)
{
printf("Who are you? ");
if(fgets(name,10,stdin)!=NULL)
printf("Glad to meet you, %s.\n",name);
}
return(0);
}
When I input something greater than 10 characters the loop skips.
Who are you? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Glad to meet you, aaaaaaaaa.
Who are you? Glad to meet you, aaaaaaaaa.
Who are you? Glad to meet you, aaaaaaaaa.
Who are you? Glad to meet you, aaaaaaaaa.
Who are you? Glad to meet you, aaaaaaaaa.
Who are you? Glad to meet you, aaaaaaaaa.
Who are you? Glad to meet you, aaaaaaa
I guess I want to clear the input buffer from the remaining characters. What will be the best way to do that...?
回答1:
check exist newline in name
.
#include <stdio.h>
#include <string.h>
int main(void){
char name[10];
for(int i=0;i<=10;i++){
printf("Who are you? ");
if(fgets(name,10,stdin)){
char *p;
if(p=strchr(name, '\n')){//check exist newline
*p = 0;
} else {
scanf("%*[^\n]");scanf("%*c");//clear upto newline
}
printf("Glad to meet you, %s.\n", name);
}
}
return(0);//Parentheses is not necessary
}
回答2:
Check if fgets()
obtained a '\n'
. If there is no '\n'
, some characters in the current line haven't been read. You can simply just ignore them.
printf("Who are you? ");
if (fgets(name, 10, stdin) != NULL) {
if (!strchr(name, '\n')) {
// consume rest of chars up to '\n'
int ch;
while (((ch = getchar()) != EOF) && (ch != '\n')) /* void */;
if (ch == EOF) /* input error */;
printf("Glad to meet you, %s.\n", name);
} else {
printf("Glad to meet you, %s.", name); // name includes ENTER
}
}
回答3:
From the documentation for fgets (emphasis mine):
Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.
So your input (which exceeds the buffer) is read in blocks of 9 chars (+1 null-terminating char).
You need to call fgets
repeatedly until the last read character is a newline (\n).
回答4:
You need to look for a \n
using something like the following:
/* flush unread input buffer */
while( ! strchr( name, '\n' ) )
if( ! fgets(name,(sizeof name),stdin) )
break;
Note: not sure if you consider this a bug or a feature, but short names will include the final \n
. This results in something like:
Glad to meet you SSS
.
来源:https://stackoverflow.com/questions/38767967/clear-input-buffer-after-fgets-in-c