0

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);
}
  • 1
    Remove the newlines from `scanf("%s\n", str);` etc. Please see [What is the effect of trailing white space in a scanf() format string?](https://stackoverflow.com/questions/19499060/what-is-the-effect-of-trailing-white-space-in-a-scanf-format-string) – Weather Vane Jan 08 '22 at 15:13
  • 1
    ... and add a space to this one: `scanf("%c\n", &x);` ==> `scanf(" %c", &x);` Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). – Weather Vane Jan 08 '22 at 15:15
  • `scanf()` *is* a very tricky function, and it is well worth spending at least an hour reading the documentation and trying things, *particularly* the way it handles whitespace both in the format string and in the input data - and that isn't consistent across the different format specifiers. – Weather Vane Jan 08 '22 at 15:18
  • Note: `scanf("%s\n", str);` will read one _word_ only - and it doesn't do bounds checking so you risk writing out of bounds. Use `scanf("%999s\n", str);` to allow for words up to 999 characters long. I suggest using `fgets` for this though. – Ted Lyngmo Jan 08 '22 at 15:18

0 Answers0