In this C++ Tutorial, i want to show you How to Get User Input, so in the previous articles we have simply printed simple values on screen using standard libraries. but the standard library provides many additional ways to interact with the user via its input/output features. basically in this article we are going to learn about cin, and how you can get inputs from the users using cin. in most program environments, the standard input by default is the keyboard, and the C++ stream object defined to access it is cin. so now we are going to create a simple example.
Also you can check more article on c++ programming language
1: C++ Introduction & Program Structure
2: C++ Variables And Data Types
So now this is the code for C++ Tutorial – How to Get User Input
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#include<iostream> #include<string> using namespace std; int main() { int num1; int num2; int sum; cout << "Please Enter First Number : " << endl; cin >> num1; cout << "Please Enter Second Number : " << endl; cin >> num2; sum = num1 + num2; cout << "Total For The Number Is : " << sum << endl; return 0; } |
The first , second and third statement declares a variable of type int
called num1,num2 and sum , basically we are going to get the input from the users via cin and store that in our two variables. this operation makes the program wait for input from cin; generally, this means that the program will wait for the user to enter some sequence with the keyboard. In this case, note that the characters introduced using the keyboard are only transmitted to the program when the ENTER (or RETURN) key is pressed. Once the statement with the extraction operation on cin is reached, the program will wait for as long as needed until some input is introduced. also you can see after getting the user input we are going to add these two values and store that in our sum variable, and at the end we want to display the sum in the screen using cout.
So run the code and this will be the result
Also you can watch the complete video for this article
Subscribe and Get Free Video Courses & Articles in your Email