Console input and output (or console I/O) refers to the interaction between a program and the user via the command line.
In C++, this is achieved using input and output streams provided by the standard library.
| Command | Concept | Description |
|---|---|---|
std::cin | Input | Receive data from standard input (usually the keyboard). |
std::cout | Output | Send data to standard output (usually the screen). |
std::cerr | Error | Send error messages to the standard error output. |
std::clog | Warnings | Similar to std::cerr, but used for warning messages. |
Data Input
std::cin is the standard input stream object in C++. It allows reading data from standard input and is commonly used to read values entered by the user via the keyboard.
To read data from std::cin, the extraction operator (>>) is used:
#include <iostream>
int main() {
int number;
std::cout << "Enter an integer: ";
std::cin >> number;
std::cout << "The entered number is: " << number << std::endl;
return 0;
}
In this example,
- The program asks the user to enter an integer.
std::cin >> number;reads the value entered by the user- Stores it in the variable
number.
Data Output
std::cout is the standard output stream object in C++. It is used to display data on the console and is commonly used to send information to the user.
To send data to std::cout, the insertion operator (<<) is used:
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Here, std::cout << "Hello, World!" << std::endl; sends the text “Hello, World!” to the console, followed by a newline (std::endl).
Errors and Warnings
Practical Examples
Basic Calculator
Below is an example of a basic calculator that uses std::cin and std::cout to perform simple arithmetic operations.
#include <iostream>
int main() {
double num1, num2;
char op;
std::cout << "Enter two numbers: ";
std::cin >> num1 >> num2;
std::cout << "Enter an operation (+, -, *, /): ";
std::cin >> op;
switch(op) {
case '+': std::cout << "Result: " << num1 + num2 << std::endl; break;
case '-': std::cout << "Result: " << num1 - num2 << std::endl; break;
case '*': std::cout << "Result: " << num1 * num2 << std::endl; break;
case '/': std::cout << "Result: " << num1 / num2 << std::endl; break;
default: std::cout << "Invalid operation" << std::endl;
}
return 0;
}
Data Reading and Report
This example shows how to read input data and then report that data back to the user.
#include <iostream>
#include <string>
int main() {
std::string name;
int age;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "Hello, " << name << ". You are " << age << " years old." << std::endl;
return 0;
}
