0

The following code has two scanf calls, but when I run it, it asks for three inputs. I assume the problem comes from \n, but why?

#include <stdio.h>
#include <stdlib.h>

int main()
{
  char *s,*t;
  s=malloc(1024);t=malloc(1024);
  scanf("%s\n",s);
  scanf("%s\n",s);
  if(s==t)
  {
    printf("Same!\n");
  }
  else
  {
    printf("Different\n");
  }
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Atrox
  • 107
  • 1
  • 6

1 Answers1

1

I assume the problem comes from \n, but why?

You are correct that this is the problem.

According to the documentation of scanf, the \n character in the format string will cause scanf to continue reading whitespace characters, until it encounters a non-whitespace character. This means that after you press ENTER, scanf will wait for you to enter a non-whitespace character, but it will only receive this character after you press ENTER again (assuming that your operating system sends input one line at a time to your program). This is most likely not what you want.

If you want to read a single line of input, I recommend that you use fgets instead.

Note that the %s scanf format specifier will only read a single word of input, whereas fgets will read an entire line of input.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
  • thanks for help, btw you can take the entire line with scanf by using %[^\n] instead of %s – Atrox Jun 21 '21 at 01:02