Section 8 - getline() for Strings and Numbers
3A.8.1 An Example that Mixes Numbers and Strings in One Program
Here is an example program that demonstrates how to safely combine strings and numbers as input in a single program. This is how I recommend doing many of the assignments which usually require both types of input. Everything is acquired using getline() and then converted using istringstream() as needed.
#include <iostream> #include <string> #include <sstream> using namespace std; int main() { double age, totalAge, averageAge; string name, allNames, userInput; // initialize accumlator variables totalAge = 0.; allNames = ""; cout << "I'm going to ask for three names and ages. Here we go.\n\n"; cout << "\n -------------- First Person --------------------\n"; cout << "First person's name: "; getline(cin, name); cout << "How old is " << name << "? "; getline(cin, userInput); istringstream(userInput) >> age; // accumulate totalAge = totalAge + age; allNames = allNames + name; cout << "\n -------------- Second Person --------------------\n"; cout << "Second person's name: "; getline(cin, name); cout << "How old is " << name << "? "; getline(cin, userInput); istringstream(userInput) >> age; // accumulate totalAge = totalAge + age; allNames = allNames + ", " + name; cout << "\n -------------- Third Person --------------------\n"; cout << "Third person's name: "; getline(cin, name); cout << "How old is " << name << "? "; getline(cin, userInput); istringstream(userInput) >> age; // accumulate totalAge = totalAge + age; allNames = allNames + ", " + name; // final report averageAge = totalAge / 3; cout << "\n------------- Results -----------------\n" << "Average age of " << allNames << ": " << averageAge << " years." << endl << endl; return 0; } /* -------------------- Sample Run (no error) ------------------ I'm going to ask for three names and ages. Here we go. -------------- First Person -------------------- First person's name: Ying Kam How old is Ying Kam? 39 -------------- Second Person -------------------- Second person's name: Mark Levine How old is Mark Levine? 59 -------------- Third Person -------------------- Third person's name: Catalina Avalon How old is Catalina Avalon? 28 ------------- Results ----------------- Average age of Ying Kam, Mark Levine, Catalina Avalon: 42 years. Press any key to continue . . . -------------------------------------------------------- */