Lecture Preview: Streams, Grid

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

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.

We will also learn about a collection object named Grid. A Grid is a two-dimensional rectangular collection that stores data in rows and columns. A grid is similar to a 2D array except with simpler and more convenient functionality.

queue

When you declare a grid, you write the type of data it will contain in < > brackets. Here are two short code examples that use a grid:

Grid<char> tictactoe;
tictactoe.resize(3, 3);    // makes a 3x3 board
tictactoe[1][1] = 'X';     // player X claims the center square of tic-tac-toe
tictactoe[0][0] = 'O';     // player O claims the top left square
tictactoe[1][0] = 'X';     // player X claims the left middle square
tictactoe[2][2] = 'O';     // player O claims the bottom right
tictactoe[1][2] = 'X';     // player X wins!
Grid<string> chessBoard;
chessBoard.resize(8, 8);
chessBoard[2][3] = "knight";
chessBoard[1][6] = "queen";
This document and its content are copyright © Marty Stepp, 2017. 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.