I'm making my first steps in ANSI C and I have run to a problem .
The code below should read an integer and then a string, but it doesn't. It reads the integer and then exits. I found out that scanf leaves a '\n' character in the input buffer and then fgets reads the '\n' and exits without asking for the string.
Code:
#include <stdio.h>
int main()
{
int x;
char st[5];
printf("Enter an integer: ");
scanf("%d", &x);
printf("Enter a line of text: ");
fgets(st, 5, stdin);
}
I tried to solve the problem with the code below. Mainly the problem was solved
but still there is a draw back. After entering the 1st string the ENTER key has to be pressed
twice in order to proceed to the second input.
If there are any ideas on how to solve this it will be much appreciated.
Code:
#include <stdio.h>
void dump_line( FILE * fp )
{
int ch;
while( getchar() != '\n' )
/* null body */;
}
int main()
{
int x;
char st[5];
printf("Enter an integer: ");
scanf("%d", &x);
dump_line(stdin);
printf("Enter a line of text: ");
fgets(st, 5, stdin);
dump_line(stdin);
printf("Enter a line of text: ");
fgets(st, 5, stdin);
}