Language: EN

cpp-entrada-y-salida-consola

Console Input and Output in C++

Console input and output (or console I/O) refers to the interaction between a program and the user through 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;
}

In this example,

  • The program prompts the user to enter an integer.
  • std::cin >> number; reads the value entered by the user
  • It stores it in the variable number.

Reading Strings

To read strings, you can use std::cin along with the extraction operator:

#include <iostream>
#include <string>

int main() {
    std::string name;
    std::cout << "Enter your name: ";
    std::getline(std::cin, name);  // Reads the entire line of input
    std::cout << "Hello, " << name << "!" << std::endl;
    return 0;
}

In this case, std::getline(std::cin, name); is used to read a complete line of text, allowing the user to enter names that contain spaces.

Error Handling

When data is entered that is not of the expected type, std::cin can enter an error state. You can check and handle these errors using the stream state:

#include <iostream>
#include <limits>

int main() {
    int number;
    std::cout << "Enter an integer: ";
    
    while (!(std::cin >> number)) {
        std::cin.clear(); // Clear the error state
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Ignore the invalid input
        std::cout << "Invalid input. Please enter an integer: ";
    }
    
    std::cout << "The entered number is: " << number << std::endl;
    return 0;
}

In this code,

  • std::cin.clear() is used to clear the error state of the stream
  • std::cin.ignore() is used to discard the invalid input.

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).

Output Formatting

You can format the output using stream manipulators:

#include <iostream>
#include <iomanip> // For format manipulators

int main() {
    double pi = 3.14159;
    std::cout << "Value of Pi: " << std::fixed << std::setprecision(2) << pi << std::endl;
    return 0;
}

In this example,

  • std::fixed and std::setprecision(2) are used to control the formatting of the floating-point number, showing two decimal places.

Stream Manipulators

In addition to std::fixed and std::setprecision, there are other useful manipulators:

CommandDescription
std::setw(n)Sets the width of the field for output.
std::leftAligns output to the left.
std::rightAligns output to the right.
std::hexChanges the numeric base of the output to hexadecimal.
std::octChanges the numeric base of the output to octal.
std::decChanges the numeric base of the output to decimal.
#include <iostream>
#include <iomanip>

int main() {
    int number = 255;
    std::cout << "Decimal: " << number << std::endl;
    std::cout << "Hexadecimal: " << std::hex << number << std::endl;
    std::cout << "Octal: " << std::oct << number << std::endl;
    return 0;
}

Errors and Warnings

Errors

std::cerr is used for error output. Unlike std::cout, std::cerr is not associated with the output buffer, so error messages are displayed immediately.

#include <iostream>

int main() {
    std::cerr << "This is an error message." << std::endl;
    return 0;
}

Warnings

std::clog is similar to std::cerr, but is generally used for log and warning messages. Its output can be redirected to different places.

#include <iostream>

int main() {
    std::clog << "This is a log message." << std::endl;
    return 0;
}

Practical Examples