4

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.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Polb
  • 640
  • 2
  • 8
  • 21
  • 3
    scanf doesn't consume the newline char ' \n' and fgets stops at that. – Magisch Dec 01 '15 at 15:16
  • 1
    Also [fgets doesn't work after scanf](http://stackoverflow.com/questions/5918079/fgets-doesnt-work-after-scanf) – nnn Dec 01 '15 at 15:20

3 Answers3

13

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(). :)

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
2

The scanf() leaves newline character after the integer, and fgets() will read it and exit.

Try reading all input with fgets().

#include <stdio.h>
#include <string.h>

int main()
{

    char buffer[255];
    int n;
    char command[255];

    fgets(buffer, sizeof(buffer), stdin);
    sscanf(buffer, "%d", &n);
    fgets(command, sizeof(command), stdin);

    return 0;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
1

Typing "3c" and pressing enter in your console will make your input buffer stdin look like this: {'3','c','\n'} and would work, since scanf consumes the 3, fgets consumes the c, and the \n would be where fgets stops.

But if you type "3" and press enter, scanf will consume the 3, and the newline character will be left, causing fgets to consume no characters.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Magisch
  • 7,312
  • 9
  • 36
  • 52