Write a C++ Program to Demonstrate Basic Input and Output Operations Using `cin` and `cout`
In any programming language, input and output operations form the core of interaction between the user and the program. In C++, these are handled using `cin` (for input) and `cout` (for output), which are part of the iostream library. These operators are used to read data from the keyboard and display results on the screen, respectively.
Understanding `cin` and `cout`
- `cin`: Stands for “console input”. It is used to accept input from the standard input device (usually the keyboard).
- `cout`: Stands for “console output”. It is used to display output to the standard output device (usually the screen).
These are used with stream operators:
* `>>` for input (`cin`)
* `<<` for output (`cout`)
C++ Code: Basic Input and Output
#include <iostream>
using namespace std;
int main() {
string name;
int age;
// Output using cout
cout << "Enter your name: ";
// Input using cin
cin >> name;
cout << "Enter your age: ";
cin >> age;
// Display the collected input
cout << "\nHello, " << name << "! You are " << age << " years old." << endl;
return 0;
}
Explanation of the Code
1. Header File:
`#include <iostream>` includes the input/output stream library, which is necessary to use `cin` and `cout`.
2. Namespace:
`using namespace std;` allows us to avoid writing `std::` before every `cin` or `cout`.
3. Variables:
`string name` and `int age` are declared to store user inputs.
4. Output Prompt:
`cout << "Enter your name: ";` prompts the user to enter their name.
5. Input Capture:
`cin >> name;` reads the input from the user and stores it in the `name` variable.
6. Similarly, `cin >> age;` captures the age.
7. Final Output:
The final message is displayed using `cout` with multiple `<<` operators, combining strings and variables in one output line.
Output Example
If the user inputs:
Enter your name: Vivek
Enter your age: 30
The program will output:
```
Hello, Vivek! You are 30 years old.
```
Comments
Post a Comment