7

If I enter str1 longer than length 10, the rest of it remains in the buffer and gets entered into my str2. How to clear the buffer before str2, so I can input 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;
}
Jens
  • 69,818
  • 15
  • 125
  • 179
dushyantashu
  • 523
  • 3
  • 9
  • 16

3 Answers3

2

After fgets(str1,10,stdin); do

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

This would clear the input buffer after 'str1' is read.

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;
}
Nithin Bhaskar
  • 686
  • 1
  • 5
  • 9
0

A different way: avoid fgets(), and read characters one by one. This allows you to handle all the conditions inside one loop:

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;
}
wildplasser
  • 43,142
  • 8
  • 66
  • 109
-1
#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;
}

Yeah, I know, what if someone enters more than 4092 characters... There's a big chance of that happening.

Dariusz
  • 21,561
  • 9
  • 74
  • 114