C++ Input/Output Functions

To read input from the user or from a file and to display output to the user or to a file, C++ Input/Output (I/O) functions are employed. The “iostream” library contains the definitions of these functions.

The input function called “cin,” which reads input from the user is the most often utilized one. The output function most frequently used, known as “cout,” shows output to the console. Getline, scanf, and printf are additional I/O functions that can be used to read input with spaces, format input, and output, respectively.

Input Functions:

  1. cin: cin >> variable;
  2. getline: getline(cin, variable);

Output Functions:

  1. cout: cout << expression;
  2. cerr: cerr << expression;
  3. clog: clog << expression;

Example:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    int num;
    string str;

    // read an integer from standard input
    cout << "Enter a number: ";
    cin >> num;

    // read a line of text from standard input
    cout << "Enter some text: ";
    getline(cin, str);

    // write the integer and text to standard output
    cout << "You entered the number " << num << " and the text \"" << str << "\"" << endl;

    // write an error message to standard error
    cerr << "An error occurred" << endl;

    // write a log message to a file
    ofstream logfile("log.txt");
    clog.rdbuf(logfile.rdbuf());
    clog << "Program started" << endl;

    return 0;
}

Output:

Enter a number: 42
Enter some text: Hello, world!
You entered the number 42 and the text "Hello, world!"
An error occurred

First, the program prompts the user to enter an integer using the cout function. The user’s input is read into the variable num using the cin function.

Next, the program prompts the user to enter some text using the cout function again. This time, the input is read using the getline function, which reads a line of text from the input stream and stores it in the variable str.

The program then uses the cout function again to print out the values of num and str, along with some additional text. Note that the string value is enclosed in double quotes using the escape sequence \”.

Next, the program uses the cerr function to output an error message to the standard error stream. This is useful for printing out error messages that should not be mixed with regular output.

Finally, the program creates an ofstream object called logfile that writes to a file called log.txt. The clog function is used to write a log message to this file, which could be useful for debugging purposes.

Overall, this program demonstrates how to read input from the user, write output to the console and to files, and output error messages to the standard error stream.