C++ Input and Output (cin / cout)
In C++, input and output operations are performed using the iostream library. The two most commonly used objects are cout for output and cin for input.
These objects allow programs to display information to the user and read data from the keyboard.
Output Using cout
The cout object is used to display output to the screen.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}
Here, the << operator is called the insertion operator. It sends data to the output stream.
Example: Printing Multiple Values
#include <iostream>
using namespace std;
int main() {
cout << "Welcome to C++ Programming";
cout << endl;
cout << "Learning Input and Output";
return 0;
}
The endl statement is used to move the cursor to the next line.
Input Using cin
The cin object is used to receive input from the user through the keyboard.
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age;
return 0;
}
In this example:
- cin reads input from the keyboard.
- >> is called the extraction operator.
- The input value is stored in the variable age.
Example Program
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
cout << "Enter your name: ";
cin >> name;
cout << "Hello, " << name;
return 0;
}
Output
Enter your name: John Hello, John
Important Notes
- cout is used for displaying output.
- cin is used for taking input from the user.
- The << operator sends data to the output stream.
- The >> operator reads data from the input stream.
Next Topic
Next, learn about C++ Operators.