C++ User Input Strings

C++ allows users to enter text into a program using cin. While this works well for single words, handling full sentences requires a different approach using getline().

Tutorials dojo strip




Receiving String Input Using cin

The cin object reads text entered by the user, storing it in a string variable.

Example

C++

If the user enters “Harley Davidson”, only “Harley” will be stored because cin stops reading after the first space.




Handling Multiple Words with getline()

To capture an entire sentence or multiple words, use getline() instead of cin.

Example

C++

Now, if the user enters “Porsche 911 Turbo”, the complete phrase will be stored properly.




Key Differences Between cin and getline()

MethodBehavior
cin >> variableReads a single word only (stops at spaces)
getline(cin, variable)Reads an entire line of text, including spaces

Tutorials dojo strip