Below is my source code. After I read the integer, the program should wait until I type a string and then press enter. However, as soon as I enter the integer, the program exits. Can you tell me where is my fault?
#include <stdio.h>
#include <string.h>
int main()
{
int n;
char command[255];
scanf("%d", &n);
fgets(command, 255, stdin);
return 0;
}
I mention that I also tried to use gets(command)
, but I get the same result.
There is a trailing newline, since you press ENTER after the integer. Eat it by changing this:
scanf("%d", &n);
to this:
scanf("%d ", &n); // this will eat trailing newline
As chux said, scanf("%d ", &n)
will not return until the user enters the number and some following non-white-space.
Relevant question: C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf
Also I have in mind my example: Caution when reading char with scanf .
Also, as Marco stated, you could use: scanf("%d\n", &n);
, which targets the newline specifically.
There is also this possibility:
#include <stdio.h>
#include <string.h>
int main()
{
int n;
char command[255], newline;
scanf("%d", &n);
scanf("%c", &newline); // eat trailing newline
fgets(command, 255, stdin);
return 0;
}
However, I would personally use two fgets()
and no scanf()
. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With