Section 4 - User Input of Strings

3A.4.1 getline()

Okay, are you ready to have a conversation with your user?  The thing about that is, you have to be ready. I was learning Spanish many years ago during which period I traveled to Madrid.  I finally got the hang of expressing myself.  The trouble was, when I asked questions, I got answers: quickly spoken, long, elaborate answers that I could not understand.  We are in a similar situation.  We can ask the user questions, but we  have to make sure we know what to do with answers that the user gives us.

The easiest way to ask questions meant for user response in a C++ console application is by stating the question with a cout statement, then reading in the results using a getline() method call.

Terminology

When we use a method that someone has written, we say we are calling or invoking the method.  Here we will be calling or invoking the getline() method.  When we create our own methods, we say we are defining a method.  We have been defining our own main() methods all along.

Here is how it works:

#include <iostream>
#include <string>
using namespace std;

int main()
{
// Declare a string reference to hold the user's answer
string strUserAnswer;

// ask the question and get the answer
cout << "What's your name? ";
getline(cin, strUserAnswer);

cout << "Hello " + strUserAnswer + "\n";

return (0);
}

It's that simple.  When we run that code, it will result in the following :

console output

There are several things to notice about this source and run:

3A.4.2 Your High School

Here is another example:

#include <iostream>
#include <string>
using namespace std;

int main()
{
// declare some string variables
string strUserAnswer;
string strQuestion;
string strFinalStatement;

// Prepare a question for the user
strQuestion = "What high school did you attend? ";

// Show the user the question and get a response
cout << strQuestion;
getline(cin, strUserAnswer);

// build up a final statement using the user's input
strFinalStatement = "Really? You went to " + strUserAnswer + "?\n";
strFinalStatement = strFinalStatement + "You must know Doug Feiger!\n\n\n";

// show the final output
cout << strFinalStatement;

return (0);
}

The output of a sample run:

What high school did you attend? Southfield High
Really? You went to Southfield High?
You must know Doug Feiger!


Press any key to continue . . .