Reputation: 194
Here is an example of the problem I face:
void print() {
printf("Hello");
}
int main() {
char a[LENGTH]; //LENGTH equals 20
printf("Please enter something: ");
fgets(a, LENGTH, stdin);
print();
return 0;
}
The program shows 'Please enter something: ' on the screen and doesn't let the user enter the string using the fgets() function. It moves directly to the print() function, therefore printing 'Hello' on the screen.
Why does this happen? Is there any way to fix it?
EDIT:
The same problem happens with this code, too:
void prints(){
printf("Hello world, how are you?");
}
int main() {
printf("blah\n");
printf("blah\n");
printf("blah\n");
printf("blah\n");
printf("blah\n");
printf("blah\n");//all these printfs are necessary.
printf("Enter a number: ");
fflush(stdout);
fflush(stdin);
int number;
scanf(" %d", &number);
printf("Please write something: \n");
char a[MAXSTRING];
fgets(a, MAXSTRING, stdin);
prints();
}
Upvotes: 0
Views: 2429
Reputation: 73444
Answer to the updated question; change this:
scanf(" %d", &number);
printf("Please write something: \n");
to this:
scanf(" %d", &number);
getchar();
printf("Please write something: \n");
The issue is relatie to the Caution with scanf() example we talked over before. The user inputs a number and he does what? He hits enters!
scanf()
does not consume that (you told it to read a number, with %d
), thus a newline (which came up from the enter stroke) is kept in the input buffer. You then call fgets()
and finds something in the input buffer, so it acts on it.
A simple solution would be to use getchar(), to consume the newline, scanf()
didn't collect, so that the input buffer is empty, when fgets()
is called.
Change this:
printf("Please enter something: ");
to this:
printf("Please enter something: \n");
to consume the newline!
Read the ref please:
Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.
Upvotes: 1