User Input
We already know how to output the data with the object cout
and operator <<
. However, sometimes we need to get values directly from the user. To enable this operation use cin
in combination with the extraction operator >>
.
cin >> x; // Get the value for the variable x
For example, here we want to get the value for the variable a and output it:
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
01 #include <iostream>
02 using namespace std;
03
04 int main() {
05 // Declare the variable
06 int a;
07 // Print the message for user to get the value
08 cout << "Print a number: ";
09 // Get user input
10 cin >> a;
11 // Display the input of the user
12 cout << "Your number is: " << a;
13
14 return 0;
15 }
12345678910111213141516171801 #include <iostream> 02 using namespace std; 03 04 int main() { 05 // Declare the variable 06 int a; 07 // Print the message for user to get the value 08 cout << "Print a number: "; 09 // Get user input 10 cin >> a; 11 // Display the input of the user 12 cout << "Your number is: " << a; 13 14 return 0; 15 }
In the line #9 the user print the value which will be stored in the variable a
.
Task
Swipe to start coding
Let’s write the simple code to output the age of the user.
- Declare the variable
age
type ofint
. - Get the value from the user which will be stored in the variable
age
. - Display the variable
age
.
Don’t forget about semicolon ;
at the end of statements.
Solution
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;
int main() {
// Declare the variable
int age;
// Print the message
cout << "Type how old are you: ";
// Get user's input
cin >> age;
// Display the input of the user
cout << "You are " << age << " years old";
return 0;
}
Everything was clear?
Thanks for your feedback!
Section 2. Chapter 3
single
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;
int main() {
// Declare the variable
_ _ _
// Print the message
cout << "Type how old are you: ";
// Get user's input
_ _ _
// Display the input of the use
_ _ _ << "You are " << _ _ _ << " years old";
return 0;
}
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat