Lesson 14-C++ iostream Library

C++’s iostream library provides an object-oriented input-output stream mechanism, allowing programs to perform input and output operations in a more type-safe and flexible way. The iostream library is part of the C++ standard library and replaces the stdio.h library from C, offering higher-level abstractions.

Basic Components of the iostream Library:

Header Files:

  • <iostream>: Contains definitions of basic input-output stream classes.
  • <iomanip>: Provides formatting manipulators for input-output streams.
  • <fstream>: Used for file input-output operations.
  • <sstream>: Used for string stream operations.

IO Objects Cannot Be Copied or Assigned

    1. IO objects cannot be stored in containers.
    1. Function parameters and return types cannot be stream types.
    1. Parameters and return types are generally references to streams.
    1. Reading from or writing to an IO object changes its state, so the passed and returned references cannot be const.

Condition States

StateExplanation
strm::iostateA machine-independent type that provides complete functionality for expressing condition states
strm::badbitUsed to indicate that the stream has collapsed
strm::failbitUsed to indicate that an IO operation failed
strm::eofbitUsed to indicate that the stream has reached end-of-file
strm::goodbitUsed to indicate that the stream is not in an error state; this value is guaranteed to be zero
s.eof()Returns true if the eofbit of stream s is set
s.fail()Returns true if the failbit of stream s is set
s.bad()Returns true if the badbit of stream s is set
s.good()Returns true if stream s is in a valid state
s.clear()Resets all condition state bits in stream s, setting the stream state to valid; returns void
s.clear(flags)Resets the specified condition state bits in stream s; returns void
s.setstate(flags)Sets the corresponding condition state bits in stream s according to the given flags; returns void
s.rdstate()Returns the current condition state of stream s; return type is strm::iostate

In the table above, strm is an IO type (such as istream), and s is a stream object.

Namespace:

  • std: All I/O classes and functions are defined in this namespace.

Main Classes:

  • std::ios_base: Base class for all stream classes, defining some basic operations.
  • std::istream: Input stream class, inherited from std::ios_base.
  • std::ostream: Output stream class, inherited from std::ios_base.
  • std::iostream: Stream class with both input and output capabilities, inherited from std::istream and std::ostream.
  • std::fstream: File stream class, used for file read/write operations.
  • std::stringstream: String stream class, used for string read/write operations.

Predefined Objects:

  • std::cin: Standard input stream object, type is std::istream.
  • std::cout: Standard output stream object, type is std::ostream.
  • std::cerr: Standard error output stream object, type is std::ostream, unbuffered, outputs immediately.
  • std::clog: Standard error output stream object, type is std::ostream, buffered.

fstream-Specific Operations

OperationExplanation
fstream fstrm;Creates an unbound file stream.
fstream fstrm(s);Creates a file stream and opens the file named s; s can be a string or a char pointer
fstream fstrm(s, mode);Similar to the previous constructor, but opens the file in the specified mode
fstrm.open(s)Opens the file named s and binds it to fstrm
fstrm.close()Closes the file bound to fstrm
fstrm.is_open()Returns a bool indicating whether the file associated with fstrm is successfully opened and not yet closed

In the table above, fstream is a type defined in the fstream header, and fstrm is a file stream object.

File Modes

File ModeExplanation
inOpen for reading
outOpen for writing
appSeek to the end of the file before each write
ateSeek to the end of the file immediately after opening
truncTruncate the file
binaryPerform IO in binary mode

String Streams

  • The sstream header defines three types to support in-memory IO:
    • istringstream reads data from a string.
    • ostringstream writes data to a string.
    • stringstream can read from and write to a given string.

Basic Usage

Output:

  • Use std::cout to output data:
std::cout << "Hello, World!" << std::endl;
  • Use std::endl to control line breaks:
std::cout << "Line 1" << std::endl;
std::cout << "Line 2" << std::endl;
  • Use formatting manipulators:
std::cout << std::setw(10) << "Value" << ": " << 42 << std::endl;

Input:

  • Use std::cin to get input:
int number;
std::cout << "Enter a number: ";
std::cin >> number;
std::cout << "You entered: " << number << std::endl;

Example Code:

Below is a simple example demonstrating how to use the iostream library for input and output operations.

#include <iostream>

int main() {
    std::cout << "Please enter your name: ";
    std::string name;
    std::cin >> name;
    std::cout << "Hello, " << name << "!" << std::endl;

    int age;
    std::cout << "Please enter your age: ";
    std::cin >> age;
    std::cout << "You are " << age << " years old." << std::endl;

    return 0;
}

Formatted Output:

In addition to basic input and output, the iostream library provides various methods for formatted output, such as setting width, precision, etc.

#include <iostream>
#include <iomanip>

int main() {
    double pi = 3.14159265358979323846;
    std::cout << "Pi with default precision: " << pi << std::endl;
    std::cout << "Pi with 2 decimal places: " << std::fixed << std::setprecision(2) << pi << std::endl;
    std::cout << "Pi with 6 decimal places: " << std::setprecision(6) << pi << std::endl;
    std::cout << "Pi with width 10: " << std::setw(10) << pi << std::endl;

    return 0;
}

Formatting Manipulators

The iostream library provides many formatting manipulators to help you control output format more precisely. Here are some commonly used manipulators:

std::setw:

  • Sets the output field width.
  • For example: std::setw(10) sets the output field width to 10.

std::setfill:

  • Sets the fill character.
  • For example: std::setfill('-') uses the - character to fill empty parts.

std::setprecision:

  • Sets the number of decimal places for floating-point numbers.
  • For example: std::setprecision(2) sets floating-point numbers to retain two decimal places.

std::fixed and std::scientific:

  • std::fixed: Outputs floating-point numbers in fixed decimal format.
  • std::scientific: Outputs floating-point numbers in scientific notation.

std::left and std::right:

  • std::left: Sets left alignment.
  • std::right: Sets right alignment.

std::boolalpha:

  • Outputs boolean values as text, such as true and false.

std::showpos:

  • Displays the sign for positive numbers.

std::uppercase:

  • Outputs hexadecimal values in uppercase letters.

Example Code:

#include <iostream>
#include <iomanip>

int main() {
    double pi = 3.14159265358979323846;
    bool flag = true;

    std::cout << "Pi: " << std::setw(10) << std::setfill('0') << std::setprecision(2) << std::fixed << pi << std::endl;
    std::cout << "Flag: " << std::boolalpha << flag << std::endl;
    std::cout << "Hexadecimal value: " << std::hex << std::uppercase << 255 << std::endl;

    return 0;
}

Error Handling

When using the iostream library, various errors may occur, such as incorrect input format, failure to open a file, etc. The iostream library provides methods to check and handle these errors.

fail Method:

  • Checks if the stream is in an error state.
  • For example: std::cin.fail().

clear Method:

  • Clears the stream’s error flags.
  • For example: std::cin.clear().

eof Method:

  • Checks if the stream has reached end-of-file.
  • For example: std::cin.eof().

bad Method:

  • Checks if the stream is in a severe error state.
  • For example: std::cin.bad().

Example Code:

#include <iostream>

int main() {
    int number;
    std::cout << "Enter an integer: ";
    std::cin >> number;

    if (std::cin.fail()) {
        std::cin.clear(); // Clear error flag
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Ignore invalid input
        std::cout << "Invalid input. Please enter an integer." << std::endl;
    } else {
        std::cout << "You entered: " << number << std::endl;
    }

    return 0;
}

File Streams

The file stream classes std::ifstream and std::ofstream are used to read data from and write data to files, respectively.

std::ifstream:

  • Used to read data from a file.
  • For example: std::ifstream file("input.txt");.

std::ofstream:

  • Used to write data to a file.
  • For example: std::ofstream file("output.txt");.

Example Code:

#include <iostream>
#include <fstream>

int main() {
    std::ofstream outputFile("output.txt");
    if (!outputFile.is_open()) {
        std::cerr << "Failed to open output file." << std::endl;
        return 1;
    }

    outputFile << "Hello, World!" << std::endl;
    outputFile.close();

    std::ifstream inputFile("output.txt");
    if (!inputFile.is_open()) {
        std::cerr << "Failed to open input file." << std::endl;
        return 1;
    }

    std::string line;
    while (std::getline(inputFile, line)) {
        std::cout << line << std::endl;
    }

    inputFile.close();

    return 0;
}

String Streams

The string stream class std::stringstream allows treating strings as streams for reading and writing data.

std::stringstream:

  • Can be used both as an input stream and an output stream.
  • For example: std::stringstream ss;.

Example Code:

#include <iostream>
#include <sstream>

int main() {
    std::stringstream ss;
    ss << "Hello, World!";

    std::string str;
    ss >> str; // Read the first word
    std::cout << "First word: " << str << std::endl;

    std::string rest;
    std::getline(ss, rest); // Read the remaining string
    std::cout << "Rest: " << rest << std::endl;

    return 0;
}

Conditional Output

Sometimes, you may need to decide whether to output information based on certain conditions. This can be achieved using std::boolalpha or custom conditional expressions.

Example Code:

#include <iostream>

int main() {
    bool condition = true;

    // Use std::boolalpha to output boolean values
    std::cout << "Condition is: " << std::boolalpha << condition << std::endl;

    // Use conditional expression to decide output
    (condition ? std::cout : std::cerr) << "This message will be printed." << std::endl;

    return 0;
}

Exception Handling

Although the iostream library does not throw exceptions by default, you can enable exception handling by setting an exception mask. This way, when a stream error occurs, an exception is thrown instead of just setting an error flag.

Setting Exception Mask:

  • Use the std::ios_base::exceptions method to set the exception mask.
  • For example: std::cin.exceptions(std::ios_base::failbit | std::ios_base::badbit);.

Catching Exceptions:

Use a try-catch block to catch exceptions.

Example:

try {
    std::cin >> number;
} catch (const std::exception& e) {
    std::cerr << "Exception caught: " << e.what() << std::endl;
}

Example Code:

#include <iostream>

int main() {
    int number;
    std::cin.exceptions(std::ios_base::failbit | std::ios_base::badbit);

    try {
        std::cout << "Enter an integer: ";
        std::cin >> number;
        std::cout << "You entered: " << number << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Exception caught: " << e.what() << std::endl;
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }

    return 0;
}

Custom Stream Operators

You can define input and output operators for your own classes so that you can directly use the << and >> operators to read and write objects of custom types.

Defining Output Operator:

Overload the operator<< function.

Example:

std::ostream& operator<<(std::ostream& os, const MyClass& obj);

Defining Input Operator:

Overload the operator>> function.

Example:

std::istream& operator>>(std::istream& is, MyClass& obj);

Example Code:

#include <iostream>

class Person {
public:
    std::string name;
    int age;

    Person(const std::string& name, int age) : name(name), age(age) {}

    friend std::ostream& operator<<(std::ostream& os, const Person& p) {
        os << "Name: " << p.name << ", Age: " << p.age;
        return os;
    }

    friend std::istream& operator>>(std::istream& is, Person& p) {
        std::cout << "Enter name: ";
        is >> p.name;
        std::cout << "Enter age: ";
        is >> p.age;
        return is;
    }
};

int main() {
    Person person("", 0);

    std::cout << "Enter person details: ";
    std::cin >> person;

    std::cout << "Person details: " << person << std::endl;

    return 0;
}
Share your love