C++ Input and Output
We know that taking data inputs and displaying outputs are important parts of a computer program.
As we have already learnt that C++ application can output (print) the result to the monitor using cout
(which is an object of the ostream class and denotes the standard output stream).
Now, we will see that our application will get user input from keyboard using cin
(which is an object of the istream class and indicates the standard input stream).
The <iostream> is the library header file that defines the standard input/output stream objects.
Getting User Input
The cin
is a predefined variable that reads data from the keyboard with the extraction operator (>>
).
In the given example, we are expecting two input values.
Then we print the resulting sum by adding the two numbers.
As usual, our application displays the result using cout
with the insertion operator (<<
).
See the example C++ code below.
//input.cpp
#include <iostream>
using namespace std;
int main() {
int a, b, sum;
cout << "Enter value of a: ";
cin >> a;
cout << "Enter value of b: ";
cin >> b;
sum = a + b;
cout << "Sum: " << sum;
return 0;
}
Output:
Enter value of a: 10
Enter value of b: 20
Sum: 30
Displaying Output
We have seen that the combination of the cout
object and the <<
operator is used to output values to the display device (i.e. monitor).
Now, we can insert a new-line character after every line by using endl (equivalent to the \n
character).
//output.cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello" << endl;
cout << "from" << endl;
cout << "TechGuru";
return 0;
}
Hello
from
TechGuru