Lecture Preview: Streams

(Suggested book reading: Programming Abstractions in C++, Chapters 3-4)

Today we will learn about the C++ stream objects that perform input and output (called "I/O") from the console or files. Here is an example of using a stream to read a file and print its contents:

#include <fstream>
#include <iostream>
#include <string>
#include "console.h"
using namespace std;

int main() {
    // read and print every line of a file
    ifstream input;
    input.open("poem.txt");
    string line;
    while (getline(input, line)) {
        cout << line << endl;
    }
    input.close();
    return 0;
}

This code uses two different stream objects:

  1. input is an input file stream, or ifstream.
  2. And you already know about cout, which does console output.
This document and its content are copyright © Marty Stepp and Julie Zelenski, 2019. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the authors' expressed written permission.