#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...?
Clearing input buffer in C/C++The function fflush(stdin) is used to flush or clear the output buffer of the stream. When it is used after the scanf(), it flushes the input buffer also. It returns zero if successful, otherwise returns EOF and feof error indicator is set.
To avoid Buffer Overflow, fgets() should be used instead of gets() as fgets() makes sure that not more than MAX_LIMIT characters are read.
buffer is a char array or chunk of memory where the characters fetched are stored. size is the size of the buffer , the same value. The fgets() function reads one less than the size value to ensure that the input string is capped with a null character, \0 .
The fgets() function stores the result in string and adds a null character (\0) to the end of the string. The string includes the new-line character, if read. If n is equal to 1, the string is empty.
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
}
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With