📜  c++ konsolenausgabe - C++ (1)

📅  最后修改于: 2023-12-03 14:59:45.082000             🧑  作者: Mango

C++ Konsolenausgabe

In C++, "Konsolenausgabe" refers to the act of displaying output in the console window. This is done using the iostream library, which provides streams for working with input/output.

Grundlagen

To output text to the console, we use the cout object, which is defined in the iostream library. Here's an example:

#include <iostream>

int main() {
    std::cout << "Hello, world!" << std::endl;
    return 0;
}

In this example, we include the iostream header file and use the std::cout object to output the text "Hello, world!" to the console. The std::endl manipulator is used to add a newline character to the output.

Eingaben vom Benutzer

We can also read input from the console using the cin object, which is also defined in the iostream library. Here's an example that reads a number from the console and outputs it:

#include <iostream>

int main() {
    int num;
    std::cout << "Enter a number: ";
    std::cin >> num;
    std::cout << "You entered: " << num << std::endl;
    return 0;
}

In this example, we declare an integer variable num, output a message to the console prompting the user to enter a number, read the input using std::cin, and output the value of num using std::cout.

Manipulatoren

Manipulators are used to format the output in various ways. Here are some examples:

  • std::setw(n) sets the field width to n characters.
  • std::setprecision(n) sets the number of decimal places to n.
#include <iostream>
#include <iomanip>

int main() {
    double pi = 3.14159265359;
    std::cout << std::setw(10) << "Pi: " << std::setprecision(3) << pi << std::endl;
    return 0;
}

In this example, we use the std::setw() manipulator to set the field width to 10 characters and the std::setprecision() manipulator to set the number of decimal places to 3. The output would be:

        Pi: 3.14
Zusammenfassung

In C++, Konsolenausgabe can be achieved using the iostream library, specifically the std::cout object. Input can be read from the console using the std::cin object. Manipulators can be used to format the output in various ways.