1

I'm having some problems running the following code. If I provide more than five characters of input to the scanf method feeding array a, the rest of the characters go into array b and I don't get to provide input again. I tried using fflush(), but it didn't help. What's going on, and how can I fix it?

#include<stdio.h>

int main()
{
 char a[6];
 char b[20];

 printf("Enter any string :\n");
 scanf("%5s",a);

 printf("%s\n",a);

 fflush(stdin); 

 scanf("%s",b);
 printf("%s\n",b);

 return 0;
}
Pops
  • 30,199
  • 37
  • 136
  • 151
Omkant
  • 9,018
  • 8
  • 39
  • 59
  • Maybe dupplicate to this question http://stackoverflow.com/questions/3437656/my-program-is-not-asking-for-the-operator-the-second-time – Bang Dao Sep 07 '12 at 09:07

1 Answers1

2

You should never use fflush(stdin) to clear the input-buffer, its undefined behavior, only Microsoft-CRT supports this.

#include<stdio.h>

int main()
{
 int c;
 char a[6];
 char b[20];

 printf("Enter any string :\n");
 scanf("%5s",a);

 printf("%s\n",a);

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

 scanf("%19s",b);
 printf("%s\n",b);

 return 0;
}
user411313
  • 3,930
  • 19
  • 16