Chapter 30: iostream: Standard Streams

Introduction

The <iostream> library provides functionality for input and output in C++. The standard streams provided by this library include cin, cout, cerr, and clog.

Standard Streams

  1. cin: An istream object tied to the standard input (typically the keyboard).
  2. cout: An ostream object tied to the standard output (typically the monitor).
  3. cerr: An ostream object tied to the standard error (typically the monitor), providing unbuffered output.
  4. clog: An ostream object tied to the standard error (typically the monitor), providing buffered output.

Example

#include <iostream>
#include <iomanip>

int main()
{
    char buf[10]{};
    std::cin >> std::setw(10) >> buf;
    std::cout << "Buffer content: " << buf << '\n';
    return 0;
}

Input Functions

Example

#include <iostream>

int main()
{
    char ch;
    std::cin.get(ch);
    std::cout << "Character read: " << ch << '\n';

    char str[5];
    std::cin.get(str, 5);
    std::cout << "String read: " << str << '\n';

    return 0;
}

Stream Manipulators

Formatting

#include <iostream>
#include <iomanip>

int main()
{
    std::cout.setf(std::ios::showpos); // turn on the std::ios::showpos flag
    std::cout << 10 << '\n'; // +10
    std::cout.unsetf(std::ios::showpos); // turn off the std::ios::showpos flag

    std::cout.setf(std::ios::showpos | std::ios::uppercase); // turn on the std::ios::showpos and std::ios::uppercase flag
    std::cout << std::hex << 27 << '\n'; // print 27 in hex

    return 0;
}

Manipulators

Example

#include <iostream>
#include <iomanip>

int main()
{
    std::cout << std::fixed << std::setprecision(2) << 123.456789 << '\n'; // 123.46
    std::cout << std::scientific << 123.456789 << '\n'; // 1.234568e+02
    std::cout << std::showpoint << 123.0 << '\n'; // 123.000
    return 0;
}

Stream Classes for Strings

std::stringstream

#include <sstream>
#include <iostream>

int main()
{
    std::stringstream os;
    os << "12345 67.89\n";
    std::cout << os.str();

    std::string strValue;
    os >> strValue; // Read until whitespace
    std::cout << "String value: " << strValue << '\n';

    int nValue;
    double dValue;
    os >> nValue >> dValue;
    std::cout << "Int value: " << nValue << ", Double value: " << dValue << '\n';

    os.str(""); // Erase the buffer
    os.clear(); // Reset error flags

    return 0;
}

Stream States and Flags

Flags

Member Functions

Example

#include <iostream>
#include <limits>

int main()
{
    int num;
    while (true)
    {
        std::cout << "Enter a number: ";
        std::cin >> num;

        if (std::cin.fail()) // no extraction took place
        {
            std::cin.clear(); // reset the state bits back to goodbit
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // clear out the bad input from the stream
            std::cout << "Invalid input, please try again.\n";
            continue; // try again
        }

        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // clear out any additional input from the stream
        break;
    }

    std::cout << "You entered: " << num << '\n';
    return 0;
}

Working with Files

Writing to a File

#include <fstream>
#include <iostream>

int main()
{
    std::ofstream outf{ "Sample.txt" };

    if (!outf)
    {
        std::cerr << "Uh oh, Sample.txt could not be opened for writing!\n";
        return 1;
    }

    outf << "This is line 1\n";
    outf << "This is line 2\n";

    return 0;
}

Reading from a File

#include <fstream>
#include <iostream>
#include <string>

int main()
{
    std::ifstream file{ "Sample.txt" };

    if (!file)
    {
        std::cerr << "Uh oh, Sample.txt could not be opened for reading!\n";
        return 1;
    }

    std::string strInput;
    while (std::getline(file, strInput))
        std::cout << strInput << '\n';

    return 0;
}

File Modes

std::ofstream outf{ "file.txt", std::ios::app };

// other method
outf.open("Sample.txt", std::ios::app);
outf.close();

Random File Access

std::ifstream inf{ "Sample.txt" };
inf.seekg(14, std::ios::cur); // move forward 14 bytes

Seek Flags

Ios seek flag Meaning
beg The offset is relative to the beginning of the file (default)
cur The offset is relative to the current location of the file pointer
end The offset is relative to the end of the file

Regular Expressions

Example

#include <regex>
#include <iostream>

int main()
{
    std::string str{ "Hello, World!" };
    std::regex re{ R"(\w+)" }; // word characters

    std::sregex_iterator begin{ str.begin(), str.end(), re };
    std::sregex_iterator end;

    for (auto it = begin; it != end; ++it)
        std::cout << it->str() << '\n';

    return 0;
}

Character Functions

Function Meaning
std::isalnum(int) Returns non-zero if the parameter is a letter or a digit
std::isalpha(int) Returns non-zero if the parameter is a letter
std::iscntrl(int) Returns non-zero if the parameter is a control character
std::isdigit(int) Returns non-zero if the parameter is a digit
std::isgraph(int) Returns non-zero if the parameter is printable character that is not whitespace
std::isprint(int) Returns non-zero if the parameter is printable character (including whitespace)
std::ispunct(int) Returns non-zero if the parameter is neither alphanumeric nor whitespace
std::isspace(int) Returns non-zero if the parameter is whitespace
std::isxdigit(int) Returns non-zero if the parameter is a hexadecimal digit (0-9, a-f, A-F)

Example

#include <iostream>
#include <cctype>
#include <string>
#include <ranges>

bool isValidName(const std::string& name)
{
    return std::ranges::all_of(name, [](char ch) {
        return std::isalpha(ch) || std::isspace(ch);
    });
}

int main()
{
    std::string name{ "John Doe" };
    if (isValidName(name))
        std::cout << "Valid name\n";
    else
        std::cout << "Invalid name\n";

    return 0;
}

Conclusion

The <iostream> library provides powerful tools for input and output in C++. Understanding how to use standard streams, file streams, and manipulators is crucial for effective C++ programming.