Skip to content
KALANBLON
Show contents

Chapter 2 of 6 · 20 min

Streams, files and parsing text

By the end of this chapter, you'll be able to

  • Write and read a file with ofstream, ifstream and getline
  • Parse a line of text with istringstream
  • Test a stream's state to detect read errors
  • Write functions that accept any stream with std::istream&

Writing and reading back a file

std::ofstream (output file stream) writes to a file, std::ifstream reads it. They come from <fstream>. They're RAII objects: the file is closed automatically when the object is destroyed.

#include <cstdio>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

struct Reading {
    std::string city;
    double temperature = 0;
};

int main() {
    {
        std::ofstream out("readings.txt");
        if (!out) {
            std::cout << "cannot write\n";
            return 1;
        }
        out << "Bamako;38.5\n" << "Oslo;-3\n" << "damaged line\n" << "Lima;19\n";
    }   // out is destroyed here: the file is flushed to disk and closed

    std::ifstream in("readings.txt");
    if (!in) {
        std::cout << "file not found\n";
        return 1;
    }
    std::vector<Reading> readings;
    std::string line;
    int number = 0;
    while (std::getline(in, line)) {
        ++number;
        std::istringstream stream(line);
        Reading r;
        if (std::getline(stream, r.city, ';') && stream >> r.temperature) {
            readings.push_back(r);
        } else {
            std::cout << "line " << number << " skipped: " << line << '\n';
        }
    }
    in.close();
    std::remove("readings.txt");
    for (const auto& r : readings) {
        std::cout << r.city << ": " << r.temperature << " °C\n";
    }
}
line 3 skipped: damaged line
Bamako: 38.5 °C
Oslo: -3 °C
Lima: 19 °C
  • if (!out) tests the stream's state: it's false if opening failed.
  • std::getline(in, line) reads a whole line (without the '\n') and returns the stream, which is false at the end of the file.
  • std::getline(stream, r.city, ';') reads up to the semicolon: that's the third argument, the delimiter.
  • stream >> r.temperature reads a number. If the text isn't one, the stream goes into a failed state and the expression is false: that's how the damaged line is detected.
  • The braces around the writing create a block: out is destroyed at its end, which guarantees everything is written before reading back.

On the damaged line, there's no number after the city: the stream fails, the line is skipped.

Step 5 of 5
Text description of the animation
  1. getline reads the file's first line.
  2. The string is wrapped in a stream: it's read with the same tools as a file.
  3. getline with the ';' delimiter reads up to the semicolon and consumes it.
  4. >> converts the rest to a number: the line is valid.
  5. On the damaged line, there's no number after the city: the stream fails, the line is skipped.

Code that works with every stream

std::ifstream and std::istringstream both inherit from std::istream. A function that receives a std::istream& therefore accepts any source: a file, a string, or even std::cin. It's also very handy for tests, which don't need to create a file.

std::vector<Reading> read_readings(std::istream& in);   // file, string or keyboard

std::ifstream file("readings.txt");
auto from_file = read_readings(file);

std::istringstream text("Accra;31\nDakar;29\n");
auto from_text = read_readings(text);                   // ideal for a test

To format numbers, <iomanip> provides std::fixed and std::setprecision(n) (number of decimals), as well as std::setw(n) (column width).

Your turn

Worked exercise

Worked exercise: averages by city

Write a function void averages(std::istream& in) that reads city;temperature lines, computes the average for each city and displays it with one decimal, in alphabetical order, along with the number of readings. Test it with a std::istringstream containing Dakar;30, Quito;14, Dakar;32, Quito;16 and Quito;12.

Hint 1
A std::map<std::string, std::pair<double, int>> keeps, for each city, the sum and the number of readings, and stores its keys in alphabetical order.
Hint 2
std::cout << std::fixed << std::setprecision(1) then displays every number with one decimal.
Show the solution and common mistakes
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <utility>

void averages(std::istream& in) {
    std::map<std::string, std::pair<double, int>> byCity;
    std::string line;
    while (std::getline(in, line)) {
        std::istringstream stream(line);
        std::string city;
        double t = 0;
        if (std::getline(stream, city, ';') && stream >> t) {
            auto& [sum, count] = byCity[city];
            sum += t;
            ++count;
        }
    }
    std::cout << std::fixed << std::setprecision(1);
    for (const auto& [city, data] : byCity) {
        std::cout << city << ": " << data.first / data.second << " °C (" << data.second << " readings)\n";
    }
}

int main() {
    std::istringstream text("Dakar;30\nQuito;14\nDakar;32\nQuito;16\nQuito;12\n");
    averages(text);
}
Dakar: 31.0 °C (2 readings)
Quito: 14.0 °C (3 readings)

auto& [sum, count] = byCity[city]; is a structured binding: it gives names to the pair's two members. byCity[city] creates the entry (with 0.0 and 0) if the city is new.

Common mistakes:

  • Using a std::unordered_map: the calculation is right, but the display order isn't guaranteed and can change from one machine to another.
  • Dividing two integers: with sums stored as int, 61 / 2 would give 30 instead of 30.5.

Summary

  1. 1Files, strings and the keyboard are all streams, read and written with the same tools.
  2. 2ofstream and ifstream are RAII objects: the file closes when they're destroyed.
  3. 3getline reads a line; with a delimiter, it reads up to that character.
  4. 4A stream in a failed state is false: that's how invalid data is detected.
  5. 5A function that takes a std::istream& works with any source.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.