Input and Output in C++
One of the important aspects of programming is the ability to interact with the user through input and output operations. In C++, this is accomplished using the input/output (I/O) library.
Output with cout
To display output in C++, you can use the cout
object, which is part of the iostream
library. Here's an example of how to use cout
to print "Hello, World!" to the console:
1#include <iostream>
2using namespace std;
3
4int main() {
5 cout << "Hello, World!" << endl;
6 return 0;
7}
The <<
operator is used to insert values into the cout
object, and the endl
manipulator is used to insert a newline character.
Input with cin
To get input from the user in C++, you can use the cin
object, also part of the iostream
library. Here's an example of how to use cin
to get the user's age and display it:
1#include <iostream>
2using namespace std;
3
4int main() {
5 int age;
6 cout << "Enter your age: ";
7 cin >> age;
8 cout << "Your age is " << age << endl;
9 return 0;
10}
In the above code, the >>
operator is used to extract values from the cin
object and store them in the age
variable.
This allows you to write interactive programs where the user can provide input, which the program can then process and respond to.
xxxxxxxxxx
using namespace std;
int main() {
// Simple output
cout << "Hello, World!" << endl;
// Input from user
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is " << age << endl;
return 0;
}