PadhaikoAll subjects

Stream Computation

Object Oriented Programming (ENCT 151)

Open in the Padhaiko app

7.1 Input/output stream class hierarchy

A stream is a sequence of bytes flowing between a program and a device (keyboard, screen, file, memory). Input is a flow into the program (extraction, >>) and output a flow out of it (insertion, <<). C++ provides the streams as a hierarchy of classes in <iostream>, <fstream> and <sstream>.

Stream class hierarchyText
                    ios_base
                       |
                      ios                (state flags, formatting)
                       |
        +--------------+--------------+
     istream                       ostream
        |   \                     /   |
        |    +------ iostream ----+   |
        |                              |
   ifstream / istringstream      ofstream / ostringstream
              \                     /
                fstream / stringstream (derived from iostream)

cin is an object of istream;  cout, cerr, clog are objects of ostream.
Main Stream Classes
ClassHeaderPurpose
ios<ios>Base class: state flags and formatting flags
istream<istream>Input: >>, get(), getline(), read()
ostream<ostream>Output: <<, put(), write()
iostream<iostream>Both input and output
ifstream, ofstream, fstream<fstream>File input, output, and input-output
istringstream, ostringstream<sstream>Streams attached to strings in memory

The four standard objects are cin (keyboard), cout (screen), cerr (unbuffered error output) and clog (buffered error output).

7.2 Testing stream errors

Every stream keeps state bits in ios, which can be tested with member functions.

Stream State Flags
FlagTest functionMeaning
goodbitgood()No error, ready for use
eofbiteof()End of input reached
failbitfail()An operation failed (wrong format or file not opened); the stream can be recovered
badbitbad()Serious error, data may be lost

clear() resets the flags, rdstate() returns them, and !stream or if (stream) tests for failure. After a failed extraction the bad characters stay in the stream and must be removed with ignore() (or by reading them into a string) before reading again.

Testing stream errorsC++
#include <iostream>
#include <sstream>
using namespace std;

void show(const istringstream &s) {
    cout << "good=" << s.good() << " eof=" << s.eof()
         << " fail=" << s.fail() << " bad=" << s.bad() << endl;
}

int main() {
    istringstream in("12 abc 7");
    int a = 0, b = 0, c = 0;

    in >> a;
    cout << "a = " << a << endl;
    show(in);

    in >> b;                       // "abc" is not an integer: failbit is set
    cout << "after reading abc: b = " << b << endl;
    show(in);

    in.clear();                    // reset the error state
    string junk;
    in >> junk;                    // remove the bad token "abc"
    in >> c;
    cout << "c = " << c << endl;
    show(in);

    in >> c;                       // nothing left: eofbit and failbit
    show(in);
    if (!in) cout << "stream is in an error state" << endl;
    return 0;
}
OutputText
a = 12
good=1 eof=0 fail=0 bad=0
after reading abc: b = 0
good=0 eof=0 fail=1 bad=0
c = 7
good=0 eof=1 fail=0 bad=0
good=0 eof=1 fail=1 bad=0
stream is in an error state

7.3 Unformatted input/output and formatted input/output

Unformatted I/O moves raw characters or bytes with no conversion:

Unformatted input and outputC++
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
    istringstream in("Hello World\nSecond line here\nXYZ");
    char ch;

    in.get(ch);                         // read one character
    cout.put(ch);                       // write one character
    cout << endl;
    cout << "peek: " << static_cast<char>(in.peek()) << endl;   // look without removing

    char word[20];
    in.get(word, 20);                   // read up to the newline, newline is left in the stream
    cout << "get() text: " << word << endl;
    in.ignore();                        // discard the newline

    string line;
    getline(in, line);                  // read a whole line, newline is removed
    cout << "getline(): " << line << endl;

    char buf[4] = {0};
    in.read(buf, 3);                    // read exactly 3 characters
    cout << "read(): " << buf << " (" << in.gcount() << " characters)" << endl;

    cout.write("written with write()", 7);   // write the first 7 characters
    cout << endl;
    return 0;
}
OutputText
H
peek: e
get() text: ello World
getline(): Second line here
read(): XYZ (3 characters)
written

Formatted I/O converts between text and values and is controlled by manipulators (<iomanip>) or by member functions of ios.

Formatting Tools
ManipulatorMember functionEffect
setw(n)width(n)Field width for the next item only
setprecision(n)precision(n)Digits (with fixed: digits after the point)
setfill(c)fill(c)Padding character
left, rightsetf(ios::left)Alignment inside the field
fixed, scientificsetf(ios::fixed)Floating-point notation
hex, oct, decsetf(ios::hex, ios::basefield)Number base
showbase, showpos, uppercase, boolalphasetf(...)Prefix, sign, case, true/false words
Formatted output with manipulatorsC++
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    double pi = 3.14159265;
    int n = 255;

    cout << "[" << setw(8) << 42 << "]" << endl;                       // right-aligned
    cout << "[" << left << setw(8) << 42 << "]" << right << endl;      // left-aligned
    cout << "[" << setfill('*') << setw(8) << 42 << "]" << endl;       // fill character
    cout << setfill(' ');
    cout << pi << endl;                                                // 6 significant digits
    cout << setprecision(3) << pi << endl;                             // 3 significant digits
    cout << fixed << setprecision(3) << pi << endl;                    // 3 digits after the point
    cout << scientific << pi << endl;
    cout.unsetf(ios::floatfield);
    cout << hex << n << " " << oct << n << " " << dec << n << endl;
    cout << showbase << hex << n << dec << noshowbase << endl;
    cout << boolalpha << (3 > 2) << " " << noboolalpha << (3 > 2) << endl;
    cout << showpos << 5 << " " << noshowpos << 5 << endl;
    cout << uppercase << hex << n << nouppercase << dec << endl;
    return 0;
}
OutputText
[      42]
[42      ]
[******42]
3.14159
3.14
3.142
3.142e+00
ff 377 255
0xff
true 1
+5 5
FF

7.4 Stream operator overloading

To print or read objects of a class with << and >>, overload the operators as non-member (friend) functions, because the left operand is the stream and not the object. The function takes and returns the stream by reference, which allows chaining.

Overloading << and >>C++
#include <iostream>
#include <sstream>
using namespace std;

class Complex {
    double re, im;
public:
    Complex(double r = 0, double i = 0) : re(r), im(i) {}
    friend ostream &operator<<(ostream &os, const Complex &c);
    friend istream &operator>>(istream &is, Complex &c);
};

ostream &operator<<(ostream &os, const Complex &c) {
    os << c.re << (c.im < 0 ? " - " : " + ") << (c.im < 0 ? -c.im : c.im) << "i";
    return os;                       // return the stream so that << can be chained
}

istream &operator>>(istream &is, Complex &c) {
    is >> c.re >> c.im;
    return is;
}

int main() {
    Complex a(3, 4), b;
    istringstream input("5 -2");
    input >> b;                      // reads two numbers from the stream
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    cout << "a and b: " << a << " | " << b << endl;   // chained output
    return 0;
}
OutputText
a = 3 + 4i
b = 5 - 2i
a and b: 3 + 4i | 5 - 2i

7.5 File input/output with streams

A file is read and written by creating a stream object attached to it. The steps are: (1) include <fstream>; (2) create an ofstream, ifstream or fstream object and open the file (in the constructor or with open()); (3) test that it opened; (4) read or write with >>, << and the functions above; (5) close it with close() (the destructor also closes it).

Writing, appending and reading a text fileC++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ofstream out("students.txt");            // opens for writing, creates the file
    if (!out) { cout << "cannot create file" << endl; return 1; }
    out << "Asha 85\n";
    out << "Bimal 72\n";
    out.close();

    ofstream app("students.txt", ios::app);  // append mode keeps the old contents
    app << "Chitra 91\n";
    app.close();

    ifstream in("students.txt");             // opens for reading
    string name;
    int marks, total = 0, count = 0;
    while (in >> name >> marks) {            // stops at the end of the file
        cout << name << " scored " << marks << endl;
        total += marks;
        count++;
    }
    cout << "Average = " << static_cast<double>(total) / count << endl;
    in.close();

    ifstream missing("nofile.txt");
    if (!missing) cout << "nofile.txt cannot be opened" << endl;
    return 0;
}
OutputText
Asha scored 85
Bimal scored 72
Chitra scored 91
Average = 82.6667
nofile.txt cannot be opened

7.6 File stream class hierarchy

ofstream derives from ostream, ifstream from istream and fstream from iostream; all three also use the helper filebuf, which does the real work with the file. Because of inheritance, every operation of ostream and istream (the operators, put, get, getline, write, read) works on file streams too.

File Stream Classes
ClassBase classDefault modeUsed for
ofstreamostreamios::out (truncates an existing file)Writing
ifstreamistreamios::inReading
fstreamiostreamnone: specify itReading and writing

7.7 ASCII and binary files

A text (ASCII) file stores characters; numbers are converted to digit characters by <<, and newlines may be translated on some systems. It is readable with an editor but larger. A binary file stores the bytes exactly as they are in memory, so an int always takes sizeof(int) bytes. It is compact, fast and keeps exact values, but it cannot be read by an editor and depends on the machine (size, byte order, padding).

Text and Binary Files
FeatureText fileBinary file
Modedefaultios::binary
Writing<<write()
Reading>>, getline()read()
Number 123455 bytes (characters)4 bytes (an int)
Human readableYesNo

7.8 Read/Write from file

The file open modes are combined with the | operator.

File Open Modes
ModeMeaning
ios::inOpen for reading
ios::outOpen for writing (default for ofstream, erases old contents)
ios::appAppend: every write goes to the end
ios::ateGo to the end of the file when opened, but writing may be anywhere
ios::truncDelete the old contents
ios::binaryBinary mode

Writing and reading whole objects of a structure or class uses write() and read() with a cast to const char * (or char *) and the object size:

Pattern for binary object I/OC++
out.write(reinterpret_cast<const char *>(&obj), sizeof(obj));
in.read(reinterpret_cast<char *>(&obj), sizeof(obj));

This is safe for plain structures of fixed-size members (arrays of char, int, float), but not for objects that contain pointers, std::string or std::vector, because only the pointer would be saved.

7.9 Sequential access to file

In sequential access the records are processed one after another from the beginning, as in the while (in >> name >> marks) loop of section 7.5. The loop ends when the extraction fails at the end of the file. This is simple but to reach record n all earlier records must be read.

7.10 Random access to file

In random access the program moves directly to any byte position and reads or writes there, so the record n of a file of fixed-size records starts at byte position (n - 1) * record size.

7.11 File access pointers and their manipulators

Each file stream has a get pointer (next byte to read) and a put pointer (next byte to write).

File Pointer Functions
FunctionPointerPurpose
seekg(pos) or seekg(offset, dir)getMove the read position
seekp(pos) or seekp(offset, dir)putMove the write position
tellg()getReport the read position
tellp()putReport the write position

The direction dir is ios::beg (from the beginning), ios::cur (from the current position) or ios::end (from the end). seekg(0, ios::end) followed by tellg() gives the file size.

Binary records and random accessC++
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

struct Student {
    int roll;
    char name[20];
    float marks;
};

int main() {
    Student s[3] = { {1, "Asha", 85.5f}, {2, "Bimal", 72.0f}, {3, "Chitra", 91.25f} };

    ofstream out("data.bin", ios::binary);
    out.write(reinterpret_cast<const char *>(s), sizeof(s));   // write all 3 records
    out.close();

    ifstream in("data.bin", ios::binary);
    in.seekg(0, ios::end);                                     // go to the end to find the size
    cout << "sizeof(Student) = " << sizeof(Student) << endl;
    cout << "file size = " << in.tellg() << " bytes" << endl;

    Student t;
    in.seekg(2 * sizeof(Student), ios::beg);                   // random access to record 3
    in.read(reinterpret_cast<char *>(&t), sizeof(t));
    cout << "record 3: " << t.roll << " " << t.name << " " << t.marks << endl;

    in.seekg(sizeof(Student), ios::beg);                       // record 2
    in.read(reinterpret_cast<char *>(&t), sizeof(t));
    cout << "record 2: " << t.roll << " " << t.name << " " << t.marks << endl;
    cout << "position after reading: " << in.tellg() << endl;
    in.close();

    fstream f("data.bin", ios::in | ios::out | ios::binary);   // update a record in place
    f.seekp(sizeof(Student), ios::beg);
    t.marks = 80.0f;
    f.write(reinterpret_cast<const char *>(&t), sizeof(t));
    f.seekg(sizeof(Student), ios::beg);
    f.read(reinterpret_cast<char *>(&t), sizeof(t));
    cout << "updated record 2: " << t.name << " " << t.marks << endl;
    return 0;
}
OutputText
sizeof(Student) = 28
file size = 84 bytes
record 3: 3 Chitra 91.25
record 2: 2 Bimal 72
position after reading: 56
updated record 2: Bimal 80

7.12 Testing errors during file operations

After opening a file always test it with if (!file) (or file.is_open()), because a missing file or a wrong path sets failbit. During processing eof() becomes true only after an attempt to read past the end, so the safe loop is while (in >> x) or while (getline(in, line)) and not while (!in.eof()). Use bad() and fail() to tell a hardware problem from a format error, and clear() to continue after a recoverable error.

7.13 File input/output with member functions

A class can hide the file format inside member functions such as save() and load(), so that the rest of the program deals only with objects.

A class that saves and loads its own objectC++
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

class Book {
    int id;
    char title[30];
    double price;
public:
    Book() : id(0), price(0) { title[0] = '\0'; }
    Book(int i, const char *t, double p) : id(i), price(p) { strncpy(title, t, 29); title[29] = '\0'; }
    void show() const { cout << id << " " << title << " " << price << endl; }
    void save(ofstream &f) const { f.write(reinterpret_cast<const char *>(this), sizeof(*this)); }
    bool load(ifstream &f) { return static_cast<bool>(f.read(reinterpret_cast<char *>(this), sizeof(*this))); }
};

int main() {
    ofstream out("books.dat", ios::binary);
    Book(1, "C++ Primer", 1200.5).save(out);
    Book(2, "Digital Logic", 850).save(out);
    Book(3, "Data Structures", 990.75).save(out);
    out.close();

    ifstream in("books.dat", ios::binary);
    Book b;
    int n = 0;
    while (b.load(in)) {            // returns false at the end of the file
        b.show();
        n++;
    }
    cout << n << " books read" << endl;
    return 0;
}
OutputText
1 C++ Primer 1200.5
2 Digital Logic 850
3 Data Structures 990.75
3 books read

The load() function returns true while a record was read, so the calling loop ends at the end of file without testing eof().


Worked Examples

Example 1

1 (8 marks)

The file students.txt is created with the lines "Asha 85", "Bimal 72" and later "Chitra 91" is appended. Write the program that prints each record and the average mark, and say what happens if the file name is wrong.

Create and append. ofstream out("students.txt") creates (or empties) the file, two lines are written and the file is closed. ofstream app("students.txt", ios::app) opens it again in append mode, so "Chitra 91" is added after the old lines.

Read. ifstream in("students.txt") and the loop while (in >> name >> marks) extract a name and an integer each time and stop when the extraction fails at the end of the file. The program of section 7.5 prints:

OutputText
Asha scored 85
Bimal scored 72
Chitra scored 91
Average = 82.6667
nofile.txt cannot be opened

Average. (85 + 72 + 91)/3 = 248/3 = 82.67 (printed as 82.6667 by default precision). static_cast<double>(total) prevents integer division.

Wrong file name. If nofile.txt does not exist the open fails and sets failbit, so if (!missing) is true and the program reports the error instead of reading garbage.

Answer:

Records Asha 85, Bimal 72, Chitra 91, average 82.6667; an unopened stream tests false.

Example 2

2 (10 marks)

A binary file holds three Student records (roll int, name char[20], marks float). Find the file size, read record 3 directly, and update record 2 in place. State the byte position of each record.

Record size. 4 + 20 + 4 = 28 bytes (no padding is needed because every member is already aligned to 4 bytes). The program prints sizeof(Student) = 28, so three records need 3 * 28 = 84 bytes, and tellg() after seekg(0, ios::end) reports 84.

Positions. Record 1 starts at byte 0, record 2 at 28 and record 3 at 56, that is (n - 1) * 28 for record n.

Direct read of record 3. in.seekg(2 * sizeof(Student), ios::beg) moves the get pointer to byte 56 and read() fetches the whole record without reading the first two.

Update in place. The file is opened with ios::in | ios::out | ios::binary. seekp(sizeof(Student)) moves the put pointer to byte 28, the changed record is written over the old one, and a read-back confirms the new marks. The full program and output are in section 7.11.

Answer:

sizeof(Student) = 28, file size 84 bytes; records start at bytes 0, 28 and 56; record 3 is Chitra with 91.25, and record 2 is updated to 80.

Example 3

3 (8 marks)

Write a stream insertion and extraction operator for a Complex class and use them to read the number 5 -2 and print it together with 3 + 4i.

Why friend functions. In cout << c the left operand is the stream, so operator<< cannot be a member of Complex. It is declared a friend so that it can reach the private members re and im.

Return the stream. Both operators return the stream reference (return os; and return is;) so that cout << a << " | " << b can be chained.

Output. The sign of the imaginary part is printed separately so that -2 appears as 5 - 2i. The program of section 7.4 prints:

OutputText
a = 3 + 4i
b = 5 - 2i
a and b: 3 + 4i | 5 - 2i
Answer:

a = 3 + 4i and b = 5 - 2i, printed with chained insertion operators.


Exercises

Exercises: Stream Computation

Question 1

Write a program that writes the text "to be or not to be" and "that is the question" to a file, then reads it back and counts the lines, words and characters (including the newline characters).

Program.

Counting lines, words and charactersC++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ofstream out("note.txt");
    out << "to be or not to be\nthat is the question\n";
    out.close();

    ifstream in("note.txt");
    string line;
    int lines = 0, words = 0, chars = 0;
    while (getline(in, line)) {
        lines++;
        chars += line.size() + 1;                 // +1 for the newline
        bool inWord = false;
        for (char c : line) {
            if (c != ' ' && !inWord) { words++; inWord = true; }
            else if (c == ' ') inWord = false;
        }
    }
    cout << "lines = " << lines << ", words = " << words << ", characters = " << chars << endl;
    return 0;
}

Output. The first line has 18 characters and the second 20, plus one newline each, giving 40 characters; the words are 6 + 4 = 10.

OutputText
lines = 2, words = 10, characters = 40
Answer:

lines = 2, words = 10, characters = 40

Question 2

Distinguish get(), getline() and the extraction operator >> when reading a line "Hello World" from the keyboard.

cin >> s skips leading white space and stops at the first white space, so only Hello is stored. cin.getline(buf, n) reads the whole line Hello World (up to n - 1 characters) and removes the newline from the stream. cin.get(buf, n) also reads the whole line but leaves the newline in the stream, so the next get returns immediately unless ignore() is used.

Answer:

>> reads a word; getline() reads a whole line and discards the newline; get(buf, n) reads a line but leaves the newline.

Question 3

Explain the difference between text and binary files, and between ios::app and ios::out.

A text file holds characters, so 12345 takes 5 bytes and is readable; a binary file stores the memory image, so an int takes 4 bytes and is not readable, but reading and writing is faster and exact.

ios::out (the default for ofstream) erases an existing file and starts at the beginning; ios::app keeps the contents and always writes at the end, even if the put pointer was moved.

Answer:

Text: characters, readable, larger. Binary: raw memory image, compact. out truncates the file, app adds to the end.

Question 4

Show with a program how formatted output prints 255 in decimal, hex and octal, and the number 3.14159265 with 3 significant digits, with 3 digits after the point, and in a right-aligned field of width 8 filled with *.

Program and output. The manipulators are hex, oct, setprecision, fixed, setw and setfill. Without fixed, setprecision(3) counts significant digits (3.14); with fixed it counts digits after the point (3.142). 255 is ff in hex and 377 in octal.

Formatted output with manipulatorsC++
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    double pi = 3.14159265;
    int n = 255;

    cout << "[" << setw(8) << 42 << "]" << endl;                       // right-aligned
    cout << "[" << left << setw(8) << 42 << "]" << right << endl;      // left-aligned
    cout << "[" << setfill('*') << setw(8) << 42 << "]" << endl;       // fill character
    cout << setfill(' ');
    cout << pi << endl;                                                // 6 significant digits
    cout << setprecision(3) << pi << endl;                             // 3 significant digits
    cout << fixed << setprecision(3) << pi << endl;                    // 3 digits after the point
    cout << scientific << pi << endl;
    cout.unsetf(ios::floatfield);
    cout << hex << n << " " << oct << n << " " << dec << n << endl;
    cout << showbase << hex << n << dec << noshowbase << endl;
    cout << boolalpha << (3 > 2) << " " << noboolalpha << (3 > 2) << endl;
    cout << showpos << 5 << " " << noshowpos << 5 << endl;
    cout << uppercase << hex << n << nouppercase << dec << endl;
    return 0;
}

Output.

OutputText
[      42]
[42      ]
[******42]
3.14159
3.14
3.142
3.142e+00
ff 377 255
0xff
true 1
+5 5
FF
Answer:

255 = ff (hex) = 377 (octal); 3.14, 3.142; the field [******42] shows setfill('*') with setw(8).

Question 5

After in >> a; fails on the input "abc", the next read also fails. Explain why and give the steps to recover. Test the flags for the program of section 7.2.

A failed extraction sets failbit and leaves the offending characters in the stream. While failbit is set, every later input operation does nothing. The program must therefore (1) call clear() to reset the flags and (2) remove the bad input with ignore() or by reading it into a string, and then (3) read again.

In the program of section 7.2 the first read of 12 gives good, the read of abc gives fail=1, and after clear() and removing abc the next read of 7 succeeds. Reading once more at the end gives eof=1 and fail=1.

Answer:

The failbit stays set and the bad text stays in the stream; use clear() then ignore() (or read it into a string) before reading again.

← Virtual FunctionsTemplates →