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()
.
Receiving String Input Using cin
The cin
object reads text entered by the user, storing it in a string variable.
Example
C++
x
using namespace std;
int main() {
string bikeModel;
cout << "Enter your favorite motorcycle model: ";
cin >> bikeModel; // Takes user input
cout << "Your favorite motorcycle is: " << bikeModel;
return 0;
}
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++
using namespace std;
int main() {
string carBrand;
cout << "Enter your favorite car brand: ";
getline(cin, carBrand); // Reads full input
cout << "Your favorite car brand is: " << carBrand;
return 0;
}
Now, if the user enters “Porsche 911 Turbo”, the complete phrase will be stored properly.
Key Differences Between cin
and getline()
Method | Behavior |
---|---|
cin >> variable | Reads a single word only (stops at spaces) |
getline(cin, variable) | Reads an entire line of text, including spaces |