Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C cannot read string after I read an integer [duplicate]

Tags:

c

string

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.

like image 439
Polb Avatar asked Dec 05 '22 01:12

Polb


1 Answers

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

like image 61
gsamaras Avatar answered Dec 18 '22 13:12

gsamaras