Practice Programs can generally be solved with a short program that directly applies the programming principles presented in this chapter.
Create a C-string variable that contains a name, age, and title. Each field is separated by a space. For example, the string might contain “Bob 45 Programmer” or any other name/age/title in the same format. Assume the name, age, and title have no spaces themselves. Write a program using only functions from cstring
(not the class string
) that can extract the name, age, and title into separate variables. Test your program with a variety of names, ages, and titles.
Repeat Practice Program 1 except use the class string
to extract the fields, not the cstring
functions.
Write a program that inputs a first and last name, separated by a space, into a string
variable. Use the string
functions to output the first and last initial. Embed your code into a do-while
loop. At the end of the loop ask the user if he or she would like to repeat the program. Input the user’s choice into a char
using cin
. If the character is ‘y’ then repeat the program, otherwise exit. Beware of the pitfall with newlines when cin
is mixed with getline
.
Write a function named firstLast2
that takes as input a vector of integers. The function should return true
if the vector starts or ends with the digit 2. Otherwise it should return false
. Test your function with vectors of different length and with the digit 2 at the beginning of the vector, end of the vector, middle of the vector, and missing from the vector.
Write a function named swapFrontBack
that takes as input a vector of integers. The function should swap the first element in the vector with the last element in the vector. The function should check if the vector is empty to prevent errors. Test your function with vectors of different length and with varying front and back numbers.
Do Practice Program 7.4 except change the program to use vectors of strings instead of arrays of strings.
Write a program that inputs two string variables, first
and last
, each of which the user should enter with his or her name. First, convert both strings to all lowercase. Your program should then create a new string that contains the full name in Pig Latin with the first letter capitalized for the first and last name. The rules to convert a word into Pig Latin are as follows:
If the first letter is a consonant, move it to the end and add “ay” to the end.
If the first letter is a vowel, add “way” to the end.
For example, if the user inputs “Erin” for the first name and “Jones” for the last name, then the program should create a new string with the text “Erinway Onesjay” and print it.