Here is the output from a sample run of this program:
Click here to view code image
What town do you live in?
Gas City
What state do you live in? (2-letter abbreviation)
IN
You live in
Gas City, IN
puts() automatically puts a newline at the end of every string it prints. You don’t have to add a \n
at the end of an output string unless you want an extra blank line printed.
Tip
gets() converts the Enter keypress to a null zero to ensure that the data obtained
from the keyboard winds up being a null-terminated string instead of an array of single
characters.
One of the most important reasons to use gets() over scanf() is that you can ask the user for
strings that contain embedded spaces, such as a full name (first and last name). scanf() cannot
accept strings with spaces; scanf() stops getting user input at the first space. Using the name of the
city from the code example, Gas City, with a scanf() statement would have caused data-entry
issues. This is the value of gets(). So if you went back to the favorite movie program in Chapter
15 , “Looking for Another Way to Create Loops,” and replaced the scanf() statement with
gets(), you could allow the user to type in titles with more than one word.
The Absolute Minimum
The goal of this chapter was to show you some built-in character and string functions
that help you test and change strings. The string functions presented in this chapter
work on both string literals and arrays. The character functions test for digits and
letters, and convert uppercase and lowercase characters to their opposites. Key
concepts from this chapter include:
- Use C’s built-in character-testing and character-mapping functions so your programs
don’t have to work as hard to determine the case of character data. - Use gets() to get strings and puts() to print strings.
- Use gets() when you must get strings that might contain spaces. Remember that
scanf() cannot grab strings with spaces. - Use strcat() to merge two strings.
- Don’t concatenate two strings with strcat() unless you’re positive that the first
character array can hold the strings after they’re merged. - Don’t put a newline inside the puts() string unless you want an extra line printed.