🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

C++ Basic Input/Output

C++ Input and Output Overview

1. Output (cout):

The cout object is used to send output to the standard output stream, usually the console. It is part of the iostream library.


#include <iostream>

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

In this example, the << operator is used to send the string "Hello, World!" to the standard output.

2. Input (cin):

The cin object is used to read input from the standard input stream, usually the console. It is also part of the iostream library.


#include <iostream>

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

In this example, the >> operator is used to read an integer value from the standard input and store it in the variable age.

3. Formatting Output:

You can format the output using manipulators, as discussed earlier. For example:


#include <iostream>
#include <iomanip>

int main() {
    double pi = 3.1415926535;

    std::cout << std::fixed << std::setprecision(2) << "Value of pi: " << pi << std::endl;

    return 0;
}

This example sets the precision for floating-point output and uses fixed-point notation.

4. Reading and Writing Strings:


#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;
}

Here, getline is used to read a line of text (including spaces) into the string variable name.

5. File I/O:

C++ also supports file input and output using the fstream class.


#include <iostream>
#include <fstream>

int main() {
    std::ofstream outputFile("output.txt");

    if (outputFile.is_open()) {
        outputFile << "This is a line in the file." << std::endl;
        outputFile << "Another line." << std::endl;
        outputFile.close();
    } else {
        std::cerr << "Unable to open the file." << std::endl;
    }

    return 0;
}

In this example, ofstream is used to create and write to a text file named "output.txt."

These are basic examples of input and output operations in C++. As you progress, you'll encounter more advanced features and techniques, such as error handling, binary file I/O, and custom stream manipulators.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.