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. Using numbers (0 is converted to false, non-zero value is converted to true)
2. Using strings ("true" or "false" are converted to true or false respectively)
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.
Cheat sheet
To get input from a user in C++, use std::cin with the extraction operator >>:
int age;
std::cout << "Enter your age: ";
std::cin >> age;The extraction operator automatically converts input to the appropriate data type:
// For integers:
std::cin >> intVariable;
// For doubles:
std::cin >> doubleVariable;
// For strings:
std::cin >> stringVariable;For boolean values, cin accepts:
- Numbers: 0 converts to false, non-zero converts to true
- Strings: "true" or "false" convert to their respective boolean values
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