How to clear the buffer when receiving multiple lines?

If I enter str1 longer than 10, the rest will remain in the buffer and be injected into my str2 . How to flush the buffer to str2 , so I can enter it?

 #include <stdio.h> int main(void) { char str1[10]; char str2[10]; fgets(str1,10,stdin); fgets(str2,10,stdin); puts(str1); puts(str2); return 0; } 
+6
source share
3 answers

After fgets(str1,10,stdin); do

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

This will clear the input buffer after reading "str1".

So your code should be

 #include <stdio.h> int main() { char str1[10]; char str2[10]; int c; str1[0]=0; str2[0]=0; fgets(str1,10,stdin); if( (str1[0]!=0) && (!strrchr(str1,'\n')) ) while((c = getchar()) != '\n' && c != EOF); fgets(str2,10,stdin); puts(str1); puts(str2); return 0; } 
+2
source

In another way: avoid fgets () and read the characters one by one. This allows you to process all conditions within one cycle:

 int main(void) { char str1[12]; char str2[13]; size_t pos; int ch; for (pos=0;;) { ch = getc(stdin); if (ch == '\n' || ch == EOF ) break; if (pos < sizeof str1 -1) str1[pos++] = ch; } str1[pos] = 0; for (pos=0;;) { ch = getc(stdin); if (ch == '\n' || ch == EOF ) break; if (pos < sizeof str2 -1) str2[pos++] = ch; } str2[pos] = 0; printf( "str1='%s', str2=%s'\n", str1, str2); return 0; } 
0
source
 #include <stdio.h> #define MAX_LEN 9 #define READBUF_LEN 4092 int main(void) { char str1[MAX_LEN+1]; char str2[MAX_LEN+1]; char readbuf[READBUF_LEN+1]; fgets(readbuf,READBUF_LEN,stdin); strncpy(str1, readbuf,MAX_LEN); str1[MAX_LEN]='\0'; fgets(readbuf,READBUF_LEN,stdin); strncpy(str2, readbuf,MAX_LEN); str2[MAX_LEN]='\0'; puts(str1); puts(str2); return 0; } 

Yes, I know that if someone enters more than 4092 characters ... There is a high probability of this.

-1
source

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


All Articles