To read in more than a single character requires the scanf() function. This function reads what has been typed into the keyboard and converts it to a particular data type, based on the formatting code given to it (just as the printf() function prints values based on formatting codes).
To use this function to read in a word, you must first define a character string, which was also briefly mentioned in Chapter 2. For example:
char word[20];
This creates a character string called word that can be up to 20 characters in length.
Next, you would prompt the user and tell the scanf() function what type of data to expect and to which variable that data should be assigned:
printf ("Please enter a word: "); scanf ("%s", word);
Just as with the printf() function, the %s signifier indicates that scanf() should store a string value in word. Table 5.1 lists the most popular scanf() signifiers.
scanf() Signifiers | |
---|---|
Signifier | Meaning |
%c | Single character |
%d | Signed integer |
%f | Float |
%s | String |
%u | Unsigned integer |
There are some tricks to using this function. For starters, when using %s to read in a string, it will only read up until the first whitespace character (a space, a tab, or a newline). In other words, it can read only a single word at a time.
Second, if the function encounters input that does not match the formatting signifier, scanf() will not work. The scanf() function returns a value, namely the number of items it read in (not the number of characters or digits). If nothing was read, it will return a value of 0 or EOF (short for end of file) or -1 (the numeric equivalent to EOF).
Third, you should definitely add the maximum field width parameter to your signifier. This value, which should match the length of the variable to which the input is assigned, dictates the maximum number of characters to be read. So, with the word example, the better syntax is
scanf ("%19s", word);
By using this, you avoid possible input buffer overruns, where C tries to read in more characters than it can handle. The number 19 is used (instead of 20) because strings include a terminating