bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/C++/C++ Tutorial
C++•C++ Tutorial

C++ User Input Strings

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind C++ User Input Strings?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ firstName;
3Order

Put the learning moves in the order that makes the concept easiest to apply.

However, cin considers a space (whitespace, tabs, etc) as a terminating character, which means that it can only store a single word (even if you type many words):
It is possible to use the extraction operator >> on cin to store a string entered by a user:
User Input Strings

User Input Strings

It is possible to use the extraction operator >> on cin to store a string entered by a user:

Example

string firstName;
cout << "Type your first name: ";
cin >> firstName;
// get user input from the keyboard cout << "Your name is: " << firstName; // Type your first name: John // Your name is: John

However, cin considers a space (whitespace, tabs, etc) as a terminating character, which means that it can only store a single word (even if you type many words):

Example

string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;
// Type your full name: John Doe // Your name is: John

From the example above, you would expect the program to print "John Doe", but it only prints "John". That's why, when working with strings, we often use the getline() function to read a line of text. It takes cin as the first parameter, and the string variable as second:

Example

string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;
// Type your full name: John Doe // Your name is: John Doe

Previous

C++ Special Characters

Next

C++ String Namespace