0

So, I have a printf, that asks for the users middle initial, then I have a scanf under that, then I output the users middle initial. My problem is that my printf is displaying after my scanf

C Code

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

int main(void) {
    char middleInitial;

    printf("What is your middle initial? ");

    scanf(" %c", &middleInitial);

    printf("Middle initial %c", middleInitial);

}

So as you can see, there are two printf's. My scanf is running before my first printf displays the question.

Example (This is what I'm getting in my terminal)

$ ./a.exe
c
What is your middle initial? Middle initial c

What I want

$ ./a.exe
What is your middle initial? c
Middle initial c

By the way, the c is what the user inputs

  • 3
    printf uses `buffered I/O`, so in this case the buffer won't be automatically flushed because there's not a newline in your format string you pass into printf. – bruceg Apr 14 '17 at 01:08
  • Possible duplicate of [C/C++ printf() before scanf() issue](https://stackoverflow.com/questions/16877264/c-c-printf-before-scanf-issue) – underscore_d Aug 22 '19 at 14:03

2 Answers2

3

Call fflush(stdout) before your call to scanf().

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0

type fflush(stdout); just before your first scanf() should be after first printf()

In my windows pc I face the same issue. If you use different operating system you might not need it.

  • Please provide a detailed explanation to your answer, in order for the next user to understand your answer better. – Elydasian Jul 27 '21 at 08:27