String Input
Part of the Fundamentals section of Coddy's C++ journey — lesson 35 of 74.
Strings behave a bit differently then other types. There are several ways to get input into a string in C++. Here are the most common methods:
1. Using cin:
std::string str;
std::cin >> str;Note: This only reads until the first whitespace
2. Using getline() (recommended for sentences with spaces):
std::string str;
std::getline(std::cin, str);This reads entire line including spaces.
3. Using both cin and getline (when reading after cin):
int n;
std::string str;
std::cin >> n;
std::cin.ignore(); // Clear the newline from input buffer
std::getline(cin, str);Without cin.ignore(), getline would read the leftover newline instead of waiting for input
Cheat sheet
There are several ways to get string input in C++:
Using cin (reads until first whitespace):
std::string str;
std::cin >> str;Using getline() (reads entire line including spaces):
std::string str;
std::getline(std::cin, str);Using both cin and getline (when reading after cin):
int n;
std::string str;
std::cin >> n;
std::cin.ignore(); // Clear the newline from input buffer
std::getline(cin, str);Use cin.ignore() to clear the newline from the input buffer when switching from cin to getline().
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison3Variables Part 2
Type DeclarationNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementConditional OperatorRecap - If ElseNested If - Else