2 years ago

#27012

test-img

user17864936

Scanf executed before printf even with fflush(stdout)

The program I wrote should in theory ask for the character to censor with printf and then execute scanf, but printf is shown on the terminal after scanf.

I read about the buffer problem but even after using fflush(stdout) after printf, scanf still gets executed before printf in the terminal.

Here's the code:

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

int main() {
  char str[1000];
  char* ptr = &str[0];
  char x;

  printf("Please enter the string: ");
  fflush(stdout);
  scanf("%s\n", str);

  printf("Please enter the character you want to censor: ");
  fflush(stdout);
  scanf("%c\n", &x);

  for( int i = 0; i < strlen(str); i++){

    if ( *ptr == x)
    {
      *ptr = '#';
    }
    ptr++;
  }

  printf("%s\n", str);
}

c

printf

scanf

fflush

0 Answers

Your Answer

Accepted video resources