< Previous | Contents | Next >

The askText() Function

The askText() function gets a string from the user. The function is versatile and takes a parameter of type string, which it uses to prompt the user. Because of this, Im able to call this single function to ask the user for a variety of different pieces of information, including a name, plural noun, body part, and verb.

string askText(string prompt)

{

string text; cout << prompt; cin >> text; return text;

}


Tra p

image

Remember that this simple use of cin only works with strings that have no white space in them (such as tabs or spaces). So when a user is prompted for a body part, he can enter bellybutton, but medulla oblongata will cause a problem for the program.

There are ways to compensate for this, but that really requires a discussion of something called streams, which is beyond the scope of this book. So use cin in this way, but just be aware of its limitations.

image