Input and Output are preferably the most important statements in a programming language.
So far, we have seen the Output command of C++(i.e. cout << ...).
#include <iostream> using namespace std; int main() { cout << "Hello World"; return 0; }
And we are yet to look at the Input statement.
So, let us look at the Input statement. Then we will be exploring a few more ways to use the
So far, we have used variables to store values. But the variables were loaded with values.
#include <iostream> using namespace std; int main() { int x = 9; cout << "The value of x is : " << x; return 0; }
But, what if you don't want the variable x to contain a fixed value like 9. Rather you want the user to enter any value of their choice.
And this is where the Input statements comes to picture.
Just like the Output statement is called cout with << . Same way the Input statement is called as cin with >>.
Let us understand cin>> statement with the below example.
#include <iostream> using namespace std; int main() { cout << "Enter any text : "; string x; cin >> x; cout << "The text you have entered is : " << x; return 0; }
Now, if you see the Output. The first line says,
Enter any text : Hello
Now, let us go to the above code and see what happened?
In the above code, we have used the cout << statement,
cout << "Enter any text : ";
So, what happened is, the below String is Printed,
Enter any text :
Then we have declared a variable x, which is initially empty.
string x;
Then we have the statement,
cin >> x;
cin >> is used to get an input from the user, and if the user enters a value, it goes and sits inside variable x.
So, the screen is stuck, until user types any number.
In the above case, I have typed Hello.
Enter any text : Hello
And Hello goes and sits inside x.
And we got the output,
The text you have entered is : Hello
And most importantly, to use cin and cout statements we need to use iostream.
#include <iostream>
We can also call iostream as Input Output Stream.
So, we have seen how can we get a String/Text as an input.
Now, let us say, you want to get a number as an input.
Even in this case, we can also use cin >>.
#include <iostream> using namespace std; int main() { int num; cout << "Enter a number of your choice : "; cin >> num; cout << "The number you have entered is : " << num; return 0; }
A simple example of cout << ... statement would be,
#include <iostream> using namespace std; int main() { int x = 9; cout << "The value of x is : " << x; return 0; }