cin Statement
Part of the Fundamentals section of Coddy's C++ journey — lesson 34 of 74.
As of now we stored values that we thought about in variables. Programs usually don't work this way. We receive values from an outer source, a user for example.
In C++, getting input from a user is done using the cin statement. This statement provides methods to read different types of input, such as integers, floating-point numbers, and strings.
To use the cin statement, you first need to declare a variable to store the input value. Then, you can use the extraction operator >> to read the input from the standard input stream std::cin and store it in the variable. Here's how you do it:
int age;
std::cout << "Enter your age: ";
std::cin >> age;The extraction operator >> will automatically convert the input to the appropriate data type based on the variable you're storing it in. For example:
// For integers:
std::cin >> intVariable;
// For doubles:
std::cin >> doubleVariable;
// For strings:
std::cin >> stringVariable;For boolean values in C++, cin can handle input in two ways:
1. By default, cin reads only 0 (stored as false) or 1 (stored as true) into a bool. Any other input, such as 5, causes extraction to fail and sets the stream's failbit, storing false since C++11.
2. To read the words true or false directly, you must first set std::cin >> std::boolalpha; otherwise those words fail to extract.
Challenge
BeginnerWrite a program that gets input from the user (their name), and then outputs Hello, followed by the user's inputted name.
For example, if the user inputs Bob, the expected output is Hello, Bob.
You will need to:
- Create an
stringvariable to store the name. - Prompt the user to enter their name.
- Read the user's name using the appropriate
cinmethod. - Print
Hello,and the stored variable in the end.
Try it yourself
#include <iostream>
#include <string>
int main() {
// Prompt the user to enter their name
std::cout << "Enter your name: ";
// Read the user's name
std::string name;
// Print the greeting message
return 0;
}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