I l@ve RuBoard Previous Section Next Section

Exercise 1.4

Try to extend the program: (1) Ask the user to enter both a first and last name, and (2) modify the output to write out both names.

We need two strings for our extended program: one to hold the user's first name and a second to hold the user's last name. By the end of Chapter 1, we know three ways to support this. We can define two individual string objects:



string first_name, last_name; 

We can define an array of two string objects:



string usr_name[ 2 ]; 

Or we can define a vector of two string objects:



vector<string> usr_name(2); 

At this point in the text, arrays and vectors have not yet been introduced, so I've chosen to use the two string objects:



#include <iostream> 


#include <string> 


using namespace std; 





int main() 


{ 


      string first_name, last_name; 


      cout << "Please enter your first name: "; 


      cin >> first_name; 





      cout << "hi, " << first_name 


           << " Please enter your last name: "; 





      cin  >> last_name; 


      cout << '\n'; 


           << "Hello, " 


           << first_name  << ' '  << last_name 


           << " ... and goodbye!\n"; 


} 

When compiled and executed, this program generates the following output (my responses are highlighted in bold):



Please enter your first name: stan 


hi, stan Please enter your last name: lippman 





Hello, stan lippman ... and goodbye! 
    I l@ve RuBoard Previous Section Next Section