cpp-entrada-y-salida-consola

Console Input and Output in C++

  • 6 min

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.

CommandConceptDescription
std::cinInputReceive data from standard input (usually the keyboard).
std::coutOutputSend data to standard output (usually the screen).
std::cerrErrorSend error messages to the standard error output.
std::clogWarningsSimilar 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;
}
Copied!

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;
}
Copied!

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