Input and output operations in C++ involve reading data from the user (input) and displaying results to the user (output). The standard way of performing these operations is through the use of the cin
(for input) and cout
(for output) streams.
Let’s explore these concepts:
Input Operations:
Reading Data from the User:
- To read data from the user, you use the
cin
stream.
Example
#include <iostream>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
std::cout << "You entered: " << number << std::endl;
return 0;
}
In this example, std::cin >> number; reads an integer from the user and stores it in the variable number.
Reading Strings:
- Reading strings is also common using
getline
or>>
for single-word inputs.Example:
#include <iostream>
#include <string>
int main() {
std::string name;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Hello, " << name << "!" << std::endl;
return 0;
}
Output Operations:
Displaying Data to the User:
- To output data to the console, you use the
cout
stream.
#include <iostream>int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
In this example,"Hello, World!"
is displayed to the console.
Formatting Output:
- You can format the output using manipulators, like
setw
,setprecision
, etc.
#include <iostream>
#include <iomanip>
int main() {
double value = 3.14159;
std::cout << std::fixed << std::setprecision(2) << "Value: " << value << std::endl;
return 0;
}
This example sets the precision to two decimal places for thedouble
value.
Error Handling:
- It’s crucial to handle errors during input operations to ensure the program doesn’t break unexpectedly. You can check the state of the stream after an input operation:
#include <iostream>
int main() {
int number;
std::cout << "Enter a number: ";
if (std::cin >> number) {
std::cout << "You entered: " << number << std::endl;
} else {
std::cerr << "Invalid input!" << std::endl;
}
return 0;
}
Here,
std::cin >> number
returnstrue
if the input is successful andfalse
otherwise.