0

I should mention that this does work in a different environment: in our programming class we normally use the IDE codeblocks (which is find awful), so I just use the gcc compiler and vim in my terminal (I'm on arch). I didn't encounter problems until recently, when I had to read in a string which contained spaces. For that I thought using the fgets() function would be a good idea, but it created some problems. This is what the code looks like:

void addStudent() {
    struct Student student;
    printf("Name of student: ");
    fgets(student.name, 25, stdin);
}

This however does not prompt me for input in my shell, it simply continues and reads in a newline character \n immediately. Do you guys have any idea how to fix this?

alk
  • 69,737
  • 10
  • 105
  • 255
boston
  • 95
  • 1
  • 7
  • 2
    Don't mix `scanf()` with `fgets()`. Preferably use only `fgets()` (possibly followed by `sscanf()`). – pmg Dec 11 '18 at 13:08
  • 1
    Did you use any input function somewhere before this? *Especially* something like `scanf`, perhaps? – Jongware Dec 11 '18 at 13:08
  • 3
    Code presented is working as expected - the problem is likely elsewhere, which is why including a [mcve] is a good idea if you want an answer/solution to your problem – Chris Turner Dec 11 '18 at 13:09
  • 3
    The problem is associated with whatever input is read BEFORE your function is called. For example, if the last input is read using `scanf()`, a newline can be left in the input buffer, and immediately cause your call of `fgets()` to return. The solution, in that case, is to be consistent with reading input - if using `fgets()` once to read from `stdin`, use `fgets()` EVERYWHERE to read from `stdin`. More specific advice isn't possible since you haven't shown the preceeding code - you really need to provide a [mcve]. – Peter Dec 11 '18 at 13:16
  • Likely the explanation is here: https://stackoverflow.com/q/5918079/4386427 – Support Ukraine Dec 11 '18 at 13:43
  • Okay so I understand that I shouldn't use `scanf()` since it messes with stdin, but which function should I use to read an integer from stdin? – boston Dec 11 '18 at 13:54
  • 1
    @boston Use `fgets` to read a line into a buffer. Then use `sscanf` on that buffer. – Support Ukraine Dec 11 '18 at 13:58
  • Yeah that works! thanks guys – boston Dec 11 '18 at 14:02
  • @boston See https://ideone.com/Bup77r – Support Ukraine Dec 11 '18 at 14:03

1 Answers1

1

As pointed out by the comments, it's not good to combine a function like scanf() with fgets(). When scanf() is called it leaves a newline character in the input buffer which is then immediately read by fgets(), causing it to fail prompting the user.

boston
  • 95
  • 1
  • 7