0

I am new to C and am writing a very simple C program which just provides a input and repeats it back to you. The code shows the first print f which is a $ and lets you input something but will not print the text back to you. Here is the code:

char input[50];
    printf("$");
    scanf("%s\n", input);
    printf("\n %s", input);

I thought it might have been a compile issue but nothing changes. I use make token which is the name of the file.

anonymous
  • 3
  • 2

1 Answers1

4

Remove the "\n" in the scanf() format string. The trailing "\n" instructs scanf() to match any number of white space characters and it will only know when it's done when encountering a non-white space character. Meanwhile you expect it to return after reading the first "\n". Consider using fgets() instead.

#include <stdio.h>

int main() {
    char input[50];
    printf("$");
    scanf("%s", input);
    printf("\n %s", input);
}

and example session:

$abc

 abc
Allan Wind
  • 23,068
  • 5
  • 28
  • 38