0
char str[20];
scanf("%s", str);
printf("%s", str);

Input 1 --> Hi prints -->Hi(Even though I added some spaces before 'Hi')

Input 2 -->Hello World prints -->Hello(scanf terminates reading char after it encounters any whitespaces but in Input 1 it didnt act as a terminating point but was just truncated.)

  • 2
    Because that's what the language definition specifies. Why does the language definition specify such a thing? Because it's the most natural and useful thing to do in most cases. "but in Input 1 it didnt act as a terminating point but was just truncated" How can you tell one from the other? – n. m. could be an AI Aug 27 '23 at 10:48
  • It doesn't always ignore leading whitespace. Specifiers `%c` and `%[]` and `%n` do not, but adding a space in front of the `%` instructs `scanf` to filter leading whitespace here too. – Weather Vane Aug 27 '23 at 10:58
  • When `scanf` is reading for `%s` and sees a space, it must continue reading to get to the string to be read. Then it reads the string, which consists of non-white-space characters. Then when it sees a space, it is done reading the string, so it stops (and “puts back” the space). So the reason `scanf` skips leading spaces but leaves trailing spaces is simple logic: You must skip leading spaces to get to the string, and trailing spaces indicate you are done. – Eric Postpischil Aug 27 '23 at 12:55

0 Answers0