I saw a video about C++ programming today, and I saw the user input the code cin.get() instead of the usual cin >> input;
I heard that code was used so you can enter a sentence or phrase into a variable. but sometimes, when I use it, it just shows me an error?
What do I still need to make it work?
To "enter a sentence or phrase into a variable", use
getline()
, not cin.getline() or cin.get()
1 2 3 4
|
string line;
cout << "Enter a sentence or a phrase: ";
getline(cin, line);
cout << "You entered: " << line << '\n';
|
and remember to
#include <string>
Last edited on
cin.getline() works similarly, but it uses a char* and is more prone to errors, so I wouldn't bother with it usually.
cin.get() gets a single char.