Strings may be read in using the %s conversion with the function scanf() but there are some irksome restrictions. The first is that scanf() will only recognise, as an external string, a sequence of characters delimited by whitespace characters and the second is that it is the programmer's responsibility to ensure that there is enough space to receive and store the incoming string along with the terminating null which is automatically generated and stored by scanf() as part of the %s conversion. The associated parameter in the value list must be the address of the first location in an area of memory set aside to store the incoming string.
Of course, a field width may be specified and this is the maximum number of characters that are read in, but remember that any extra characters are left unconsumed in the input buffer.
Simple use of scanf() with %s conversions is illustrated in the program shown below.
main()
{
char strspace[50]; /* enough ?? */
printf("Enter a string ");
scanf("%s",strspace);
printf("The string was >>%s<<\n",strspace);
}
The program was called
str2
and a typical dialogue is illustrated below. $ str2 Enter a string fred The string was >>fred<< $ str2 Enter a string fred and joe The string was >>fred<< $ str2 Enter a string fred The string was >>fred<< $ str2 Enter a string "fred and joe" The string was >>"fred<< $ str2 Enter a string fred\ and\ joe The string was >>fred\<< $It will be noted that attempts to quote a string with internal spaces or to escape the internal spaces (both of which normally work in the Unix command environment) did not work.