C++ Output
In C++, cout sends formatted output to standard output devices, such as the screen. We use the cout object along with the << operator for displaying output.
For Example
|
1 2 3 4 5 6 7 |
#include <iostream> using namespace std; int main() { cout << "C++ Codinz"; return 0; } |
Output :
|
1 |
C++ Codinz |
How does this program work?
- We first include the iostream header file that allows us to display output.
- The cout object is defined inside the std namespace. To use the std namespace, we used the
using namespace std;statement. - Every C++ program starts with the
main()function. The code execution begins from the start of themain()function. - cout is an object that prints the string inside quotation marks
" ". It is followed by the<<operator. - return 0; is the “exit status” of the
main()function. The program ends with this statement, however, this statement is not mandatory.
Note: If we don’t include the using namespace std; statement, we need to use std::cout instead of cout.This is the preferred method as using the std namespace can create potential problems.
However, we have used the std namespace in our tutorials in order to make the codes more readable.
|
1 2 3 4 5 6 |
#include <iostream> int main() { std::cout << "C++ Codinz"; return 0; } |
C++ Input
In C++, cin takes formatted input from standard input devices such as the keyboard. We use the cin object along with the >> operator for taking input.
Example : Integer Input/Output
|
1 2 3 4 5 6 7 8 9 10 |
#include <iostream> using namespace std; int main() { int n; cout << "Enter an integer: "; cin >> n; // integer input cout << "The number is: " << n; return 0; } |
Output
|
1 2 |
Enter an integer: 1 The number is: 1 |
In the program, we used
|
1 |
cin >> n; |
to take input from the user. The input is stored in the variable n. We use the >> operator with cin to take input.
using namespace std; the statement, we need to use std::cin instead of cin.