206 Chapter 10 Character Strings
The second call to the equalStringsfunction passes the string stratwice.The
function correctly returns a truevalue to indicate that the two strings are equal, as veri-
fied by the program’s output.
The third call to the equalStringsfunction is a bit more interesting. As you can see
from this example, you can pass a constant character string to a function that is expecting
an array of characters as an argument. In Chapter 11, “Pointers,” you see how this works.
The equalStringsfunction compares the character string contained in strbto the
character string "string"and returns trueto indicate that the two strings are equal.
Inputting Character Strings
By now, you are used to the idea of displaying a character string using the %sformat
characters. But what about reading in a character string from your window (or your
“terminal window”)? Well, on your system, there are several library functions that you
can use to input character strings.The scanffunction can be used with the %sformat
characters to read in a string of characters up to a blank space, tab character, or the end
of the line, whichever occurs first. So, the statements
char string[81];
scanf ("%s", string);
have the effect of reading in a character string typed into your terminal window and
storing it inside the character array string. Note that unlike previous scanfcalls, in the
case of reading strings, the &is notplaced before the array name (the reason for this is
also explained in Chapter 11).
If the preceding scanfcall is executed, and the following characters are entered:
Shawshank
the string "Shawshank"is read in by the scanffunction and is stored inside the string
array. If the following line of text is typed instead:
iTunes playlist
just the string "iTunes"is stored inside the stringarray because the blank space after
the word scanfterminates the string. If the scanfcall is executed again, this time the
string "playlist"is stored inside the stringarray because the scanffunction always
continues scanning from the most recent character that was read in.
The scanffunction automatically terminates the string that is read in with a null
character. So, execution of the preceding scanfcall with the line of text
abcdefghijklmnopqrstuvwxyz
causes the entire lowercase alphabet to be stored in the first 26 locations of the string
array, with string[26]automatically set to the null character.