-2

To take input string in c, we can opt for 2 ways(as per my knowledge please add more if i missing something)

char name[10];
scanf(" %s",name); // First case
scanf("%[\n]s",name); // Second case

1st one will consider the string till the first blank space and 2nd will take complete sentence till the new line break as a string but to take input we need to improvise the 2nd statement as

scanf(" %[\n]s",name);

my question is what is extra spacing doing here ? because sometime my compiler will behave normally even if i will remove the 's' from scanf statement and without extra spacing before '%' but sometime it wont work.

Nishant Kumar
  • 463
  • 2
  • 9
  • 18

2 Answers2

1

The space before the % operator will make it so that any white-space before the entered string is removed as well as whatever effect the format specifiers after the % operator have on the input.

Ex: "\n\t Hello World" entered with " %[^\n]" will be recorded as "Hello World".

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
William Gerecke
  • 371
  • 2
  • 7
0

If white space character is left in first input stream and mistakenely read by next input scanf: to delete the white space character from input stream either use space before format string or use fflush (stdin) function.

YakovL
  • 7,557
  • 12
  • 62
  • 102