Classwork 26: Flash Cards
Practice working with string functions from various libraries.
Write a program that helps a middle school student memorize the capitals of the 50 united states. A sample run of your program might look like:
PT% gcc -Wall flash.c -lreadline PT% ./a.out What is the capital of New Hampshire? Nashua Wrong! The capital of New Hampshire is Concord. What is the capital of Rhode Island? Providence Right! What is the capital of Minnesota? Saint Paul Right! What is the capital of Oklahoma? quit Good-bye! PT%
Use flash.c as the starting point of the program. The main program already has two arrays of strings defined for you: states and capitals. The first one has the names of all 50 states. The second one has the names of the 50 capitals. The two arrays are coordinated, so states[i] is the name of the i-th state and capitals[i] has the name of its capital city. For example, states is "Arkansas" and capitals is "Little Rock".
The main program in flash.c also seeds the random number generator for you.
- You should use the readline() function to read the user's input. Recall that some state capitals have a two word name (e.g., Little Rock, Arkansas and Saint Paul, Minnesota). This makes scanf() difficult to use.
- Don't forget to free the string returned by readline() when you don't need the string anymore.
- When you use readline(), you must tell
gcc to use the readline library:
gcc -Wall flash.c -lreadline
- Use the strcmp() function in the string library to compare two strings.
You can use the random number generator this way:
This will store in i a random number between 0 and 49 (inclusive).
i = random() % 50 ;
Optional EmbellishmentIf you are all done with time to spare, add this feature to your program: when the user types in a wrong answer, check if the city is the capital of a different state. Then remind the user of this fact. For example:
PT% ./a.out What is the capital of New Hampshire? Providence Wrong! The capital of New Hampshire is Concord. Providence is the capital of Rhode Island.
SubmitUse the script command to record several sample runs of your program. Then, submit your program and sample run as usual:
submit cs104_chang cw26 flash.c submit cs104_chang cw26 typescript