2 Basic Input Output
2 Basic Input Output
2 Basic Input Output
In this tutorial, we will learn to use the cin object to take input from the user, and
the cout object to display output to the user with the help of examples.
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.
int main() {
// prints the string enclosed in double quotes
cout << "This is C++ Programming";
return 0;
}
Run Code
Output
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.
#include <iostream>
int main() {
// prints the string enclosed in double quotes
std::cout << "This is C++ Programming";
return 0;
}
Run Code
To print the numbers and character variables, we use the same cout object but
without using quotation marks.
#include <iostream>
using namespace std;
int main() {
int num1 = 70;
double num2 = 256.783;
char ch = 'A';
Output
70
256.783
character: A
Notes:
The endl manipulator is used to insert a new line. That's why each output is
displayed in a new line.
The << operator can be used more than once if we want to print different
variables, strings and so on in a single statement. For example:
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.
int main() {
int num;
cout << "Enter an integer: ";
cin >> num; // Taking input
cout << "The number is: " << num;
return 0;
}
Run Code
Output
Enter an integer: 70
The number is: 70
int main() {
char a;
int num;
return 0;
}
Run Code
Output