Home Segments Index Top Previous Next

707: Mainline

The s specification is for reading characters into an array. In normal use, the s specification tells scanf to skip over any following whitespace characters and to read the characters up to the next whitespace:

char input_buffer[100]; 
scanf ("%s", input_buffer); 
printf ("The author's login name is %s.\n", input_buffer); 
--- Data ---
   phw is the author's login name. 
--- Result --- 
The author's login name is phw. 

Note that scanf appends the null character, \0, to the characters actually read. Hence, the character array must be big enough to accommodate the characters in the input string plus an additional character.

Note also that you can supply a modifying number with the s read specification, in which case, after skipping any whitespace, scanf reads the input string until that number of characters have been read, or whitespace is encountered, or the end of a file is encountered:

char input_buffer[100]; 
  • scanf ("%3s", input_buffer); printf ("The author's friends never call him %s.\n", input_buffer); --- Data --- Patrick Henry Winston --- Result --- The author's friends never call him Pat.