How to clear input buffer after fgets overflow?

I am having a little problem with fgets when the input string exceeds a predefined limit.

Taking the example below:

for(index = 0; index < max; index++) {printf(" Enter the %d string : ",index+1) if(fgets(input,MAXLEN,stdin)) { printf(" The string and size of the string is %s and %d \n",input,strlen(input) + 1); removeNewLine(input); if(strcmp(input,"end") != 0) { //Do something with input } } 

Now that I have exceeded the length of MAXLEN and enter the string, I know that the input will add "\ 0" to MAXLEN -1, and that will be so. The problem occurs when I try to enter a second line that is not requested for ie

 Output : Enter the first string : Aaaaaaaaaaaaaaaaaaaa //Exceeds limit Enter the second string : Enter the third string : ....Waits input 

So, I thought I should clear the buffer in the standard way, as in C. It waits until I enter

 return 

twice. The first time it is added to the line and the next time, expecting more input with a different return. 1. Is there any method by which I can flush the buffer without making any extra return? 2. How can I implement error handling for the same? Since the return value of fgets will be Non-null, and strlen (input) gives me the accepted string size of fgets, what should I do?

thanks a lot

+4
source share
2 answers

If I understood correctly, it looks like you want to avoid double input when the input you enter is within range.

Work around would be

 for(index = 0; index < max; index++) { printf(" Enter the %d th string :",index); // if (strlen(input) >=MAXLEN ) if(fgets(input,MAXLEN,stdin)) { removeNewLine(input); if(strcmp(input,"end") != 0) // Do something with input ; } if (strlen(input) == MAXLEN-1 ) while((ch = getchar())!='\n' && ch != EOF ); } 

With the restriction that he will again ask you to enter twice when the entered characters are exactly MAXLEN-2.

Or else you can simply create your input using a character using character input.

+4
source
 while ((c=getchar()) != '\n' && c != EOF) ; 

or

 scanf("%*[^\n]%*c"); 
+3
source

Source: https://habr.com/ru/post/1498121/


All Articles