Welcome to Lesson 19!

Learning Objectives
By the end of today's class, you should know...
  • How do you read input from a file?
  • How do you write output to a file?
  • How do you use a loop to read in data from a file?
  • What is an array?
  • How do you declare an array in 2 different ways?
    • Static and Non-Static Initialization
  • How do you use a for loop to print the contents of an array?


  • Return Quiz 7
    • If you scored below a 4, you are strongly encouraged to get extra help on functions for the final by doing the following:
    • See me in office hours
    • See a TA in the lab
    • Sign up for a free half hour of tutoring on functions from a tutor in the lab
    • This is a topic you need to understand before you continue to 22B!
  • Last lab due Friday
  • Last day to submit any makeup work for this class (no more than one week late) is this Thursday's office hour
    • Don't come to this office hour if you can come to an earlier one
    • If you must come on Thursday, come early
    • This office hour will be packed!
  • No assignments or activities accepted after Thursday's office hour. No exceptions.
  • Final Exam one week from today

Review Activity

1. What will be the current value after executing this program

void increment(double num){

void decrement(double& num) {

int main() {
    double value = 4.5;
    cout << "The current value: " << value;

(a) The current value: 4.5
(b) The current value: 5.5
(c) The current value: 3.5

2. Write the following function which takes in a reference parameter:

void capitalizeLetter(char& letter);
//Given a char that is a valid letter (a-z or A-Z)
//Returns a capitalized letter
//capitalizeLetter('a') - > 'A'
//capitalizeLetter('A') -> 'A'

3. Call the above function given the starter code:

int main() {

    char letter;

    cout << "Enter a letter: ";

    cin >> letter;

    //Call the function here

    cout << "The capitalized letter is: " << letter;


Streams and File I/O

About Program I/O
  • Program I/O = Program Input/Output
    • Input to and output from programs
  • Input can be from a keyboard, mouse or file
  • Output can be to a display screen, printer or file
  • Note that files can be both input and output devices for programs
  • Advantages of file I/O:
    • Data still exists after the program ends
    • Input can be automated (rather than entered manually)
    • Output from one program can be input to another
  • To store and retrieve data in a file, we need two constructs:
    • A file
    • A file stream object
  • We will look at files first


File: a collection of data stored under a common name on a storage medium.

  • Files provide long-term storage of large amounts of data
  • Usually, you store files on durable storage mediums
    • Magnetic disks
    • Optical disks
    • Flash storage, like USB storage devices
  • Files are a single sequence of bytes

    Byte 0 Byte 1 Byte 2 ... Byte n−1 End-of-file marker

  • Since the data arranged as bytes, any type of data can be stored in a file
  • The operating system keeps track of the number of bytes in a file
  • Files must have a name
    • Naming requirements depend on the underlying operating system (OS)
  • The operating system organizes files into directories

Types of Files

  • All data in a file is ultimately just zeros and ones
  • Each binary digit can have one of two values: 0 or 1
  • A bit is one binary digit
  • A byte is a group of eight bits
  • These binary digits may represent integer values or text characters
  • It is up to the program using the file to understand the meaning and internal format of the data
  • In general, programs interpret data using two broad categories: text and binary

Text Files

  • In text files, the bits represent printable characters
  • Files are usually stored as one byte per character (ASCII)
  • Each line is delimited by end-of-line characters:
    • Macintosh (before OS-X): "\r"
    • Unix: "\n"
    • Windows: "\r\n"
  • An example of a text file is source code
  • We can read text files because each byte is interpreted by a program as textual characters
  • Some of these programs, like TextPad, then display the textual data to your computer's screen
  • Since there are many programs that read and display text, text files are called human readable

Binary Files

  • Data other than text is usually referred to as binary data
  • Each bit represents some type of encoded information
    • Such as program instructions or integer data
  • Binary files are easily read by the computer but not by humans
  • The following table compares binary and text values saved in a file
  • First we consider the value "1234" as ASCII codes and compare these bits to a binary value of 1234
  • As we can see, the bit patterns are different for the same data when stored as text or binary

Comparing Binary and Textual Data

Description Byte 0 Byte 1 Byte 2 Byte 3
"1234" as char's '1' '2' '3' '4'
"1234" as ASCII codes (bytes) 49 50 51 52
"1234" as ASCII codes (bits) 00110001 00110010 00110011 00110100
(int) 1234 as binary bits 00000000 00000000 00000100 11010010


Stream: a one-way transmission path that either delivers data to a destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.)

  • A stream connects a program to an I/O object
  • Input stream: an object that provides a sequence of bytes to a program
image depicting an input stream

  • Output stream: an object that accepts a sequence of bytes from a program
image depicting an output stream

  • cin and cout are input and output streams

File Streams

File stream: a one-way transmission path used to connect a program to a file.

  • File streams can be either input or output streams
  • File input streams receive data from a file
  • File output streams send data to a file
  • File I/O uses streams of type ifstream and ofstream
  • To declare a file input stream, we write code like:
    ifstream fin; //declares a file input stream
  • Similarly, to declare a file input stream we write code like:
    ofstream fout; //declares a file output stream
  • Each file your program uses will need a separate file stream object
Streams and Objects

  • Streams are objects and thus cin and cout are objects
  • Objects are special variables that can have a function associated with them
  • To call a function of an object, we use the dot operator
  • An example of using the dot operator is with cin is shown below

Example of File I/O

  • Let us consider an example that reads from a file and writes to a file
  • The program reads from a file named infile.txt, which contains the following values:
  • After summing the values, the program writes them to a file named outfile.txt
  • Consider the following code and try to identify:
    1. What is the name of the input stream?
    2. Which line opens a file for reading
    3. What is the name of the output stream?
    4. Which line opens a file for writing
    5. Which line reads data from the input stream?
    6. Which lines write data to the output stream?

Example Program to Read and Write Files

    Reads three numbers from the file infile.txt,
    sums the numbers, and writes the sum to the
    file outfile.txt.
#include <fstream>   // for file I/O
#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
    ifstream fin;
    if (fin.fail()) {
        cout << "Input file opening failed.\n";

    ofstream fout;
    if (fout.fail()) {
        cout << "Output file opening failed.\n";

    int first, second, third;
    fin >> first >> second >> third;
    fout << "The sum of the first 3\n"
         << "numbers in infile.txt\n"
         << "is " << (first + second + third)
         << endl;


    cout << "Processing completed\n";

    return 0;
Closing a Stream

  • After finishing reading and writing you should close the file streams
  • If you do not close an output stream, you may lose data stored in the output buffer
  • In addition, streams consume system resources and you should not keep open any more streams than needed

Procedure For File I/O

  1. Place the following include directives in your program file:
    #include <fstream>   // for file I/O
    #include <iostream>  // for cout
    #include <cstdlib>   // for exit()
    using namespace std;
  2. Declare names for input and output streams like:
    ifstream fin;
    ofstream fout;
  3. Connect each stream to a file using open() and check for failure:
    if (fin.fail()) {
        cout << "Input file failed to open.\n"; exit(-1);
    if (fout.fail()) {
        cout << "Output file failed to open.\n";
  4. If there is a failure, we need to check that the input file is stored in the same directory that the .cpp file is executing.
  5. Read or write the data:
    • Read from a file with fin like using cin:
      fin >> first >> second >> third;
    • Write to a file with fout like using cout:
      fout << "first = " << first << endl;
  6. Close the streams when finished reading and writing:

More Information

How to Save Your Files Using Eclipse

  • If you are using Eclipse for your assignments in this class, you can simply save the file in the same project folder as your program (not under src)
  • Right click on the project folder in the project explorer (right side bar)
  • Then, go to New->File from the drop down menu that appears
  • Name your file using the extension .txt
  • Note: if your project explorer is hidden, go to the following: Window->Show View->Other...->General->Project Explorer

Activity 19.1: Two Numbers

  • In this exercise we write a program that copies two numbers from an input stream to an output stream.
  • Copy the following program into a C++ file, save it as copytwo.cpp, and then compile and run the starter program to make sure you copied it correctly.
    #include <iostream>
    using namespace std;
    int main() {
        // Enter your code here
        return 0;
  • Then, let's create a text file to test our program. Open up a new file in Eclipse by right-clicking the name of the project and selecting New->File.
  • Name your file infile.txt.

  • Stop!! Did you save the file under the src folder? This is not the correct location. Drag and drop it into your main project folder.
  • We will read from this file after writing our program.

  • Place the following include directives in your source code file:
    #include <iostream>  // for cout
    #include <fstream>   // for file I/O
    #include <cstdlib>   // for exit()
    using namespace std;
  • Inside main(), declare names for the input and output streams:
    ifstream fin;
    ofstream fout;
  • Add code to connect each stream to a file using open() and check for failure:
    if (fin.fail()) {
        cout << "Input file failed to open.\n";
    if (fout.fail()) {
        cout << "Output file failed to open.\n";
  • Add statements to read two numbers from the input stream. For example, here is possible code for reading the first number:
    int first;
    fin >> first;
  • Add statements to write the two numbers to the output stream. For example, here is possible code for writing the first number:
    fout << "first = " << first << endl;
  • Close the streams when finished reading and writing:
  • Compile and run your modified program to make sure you made the changes correctly.

    Notice that you do not see any output on the screen for file reading or writing. The output stream wrote the program output to the output file.

  • Save your program source code file to submit to Canvas

Listing of copytwo.cpp

copy two program


Introduction to Arrays

Using Lists for Data

  • Often times we need to process a group of the same types of data
  • For instance:
    • Bank account transactions
    • Salaries for employees in a company
    • Test scores for a group of students
    • Temperature data over some period of time
  • Consider how we might process the following student test scores:
  • With this data, we can calculate statistics like:
    • Highest score
    • Lowest score
    • Average (mean) score
    • Difference (deviation) of each score from the average
  • We can write a program to read this data and make the calculations
  • However, to calculate the difference from the mean, we need to first find the mean
  • Thus, we have to process all the data twice: one to find the mean and another to calculate the difference of each score from the mean

Storing Lists of Data

  • If we know there are 10 inputs, we can use 10 separate variables.
int score1 = 90;
int score2 = 95;
int score3 = 87;
int score4 = 89;
int score5 = 98;
int score6 = 96;
int score7 = 85;
int score8 = 79;
int score9 = 95;
int score10 = 100;
  • However, declaring all of these variables and assigning them values is a very tedious process.
  • Now, imagine there were 100 test scores... Or, an unknown number of test scores...
  • We need another system!
  • Fortunately, C++ has techniques we can use to organize lists of data

Defining Arrays

  • An array is a collection of data items all of the same type
  • You declare an array like this:
    dataType variableName[size];
  • Where:
    • dataType: the data type of all the array items
    • variableName: the name you make up for the array
    • size: the number of data items the array can hold
  • For example, the following is the declaration of an array named scores that holds 10 values of type int:
    int scores[10]
  • Arrays like this can never change size and the array size must be set when the program is compiled
  • When defining an array, you must guess the maximum number of elements you need to store:
    const int MAX_SCORES = 10;
    int scores[MAX_SCORES];
  • The programmer must keep track of the capacity
  • We use a constant to hold the capacity of the array as shown above
  • This allows us to know the size anywhere in our code
  • If we need to change the size, we change only a single constant and recompile
  • When a program executes this statement, it creates 10 contiguous slots in memory like this:
    scores = 
  • Each of the memory slots can hold one data value

Initializing Array Items

  • We specify which slot of an array to access with the [] operator:
    scores[4] = 98;
  • The indexes of arrays are numbered starting at 0
  • We can assign a value to an array element any time after it is declared:
    const int MAX_SCORES = 5;
    int scores[MAX_SCORES];
    scores[0] = 90;
    scores[1] = 95;
    scores[2] = 87;
    scores[3] = 89;
    scores[4] = 98;
  • We can also initialize array elements in the declaration statement:
    • Called static initialization
    • We use a comma-separated list inside curly-braces
  • For example:
    int scores[] = { 90, 95, 87, 89, 98 };
  • This produces the same array as in the previous example
  • The compiler computes the size automatically by counting the items in the list
  • If we want a larger array with only the first few elements initialized, we can use:
    int scores[MAX_SCORES] = {90, 95, 87};
  • Note that if we do not assign a value to an array element, its value is not known.

Accessing Array Items

  • To access the slots in an array, we must specify which slot to use with the [] operator
  • For instance:
    scores[4] = 98;
  • The number inside the brackets is called an index or subscript
  • In C++, the slots of an array are numbered starting at 0, as shown below:
    scores = 
  • Thus, assignment to the slot with an index of 4 is put into the fifth slot

Using Slots

  • We declared our example array with a data type of int:
    int scores[10];
  • Because scores is an array containing int values, we can use a slot, such as scores[4], just like any variable of type int:
    cout << scores[4] << endl;
  • This includes using a slot as an argument to a function with a parameter of the same type:
    void myFun(int singleScore);

Using Arrays to Collect Data Items

  • Note that the index of an array can be any integer value
  • Thus, we can use an integer variable for the index
  • We can use an integer variable with a loop to read data into the array
  • Also, we can display the contents of an array using a loop
  • The following program shows an example of collecting and displaying data items

Example Program Using Arrays to Collect and Display Data Items

#include <iostream>
using namespace std;

int main() {
    const int MAX_SCORES = 10;
    int scores[MAX_SCORES];

    cout << "Enter " << MAX_SCORES << " scores:\n";
    for (int i = 0; i < MAX_SCORES; i++) {
        cin >> scores[i];

    cout << "You entered:\n";
    for (int i = 0; i < MAX_SCORES; i++) {
        cout << scores[i] << endl;

    return 0;

Activity 19.2: My First Array (10pts)

  • Open a new C++ file in Eclipse called array.cpp.
  • Inside main(), add a statement to define an array named names that is suitable for holding a list of three (3) names.
  • Compile your code to make sure it has correct syntax.

    If you have problems, ask a classmate or the instructor for help as needed.

  • Assign values to each of the array elements like:
    names[0] = "Abel Ableson";
  • Add a for-loop to display all three array values.
  • Compile your code to make sure it has correct syntax.

    If you have problems, ask a classmate or the instructor for help as needed.

  • When you are finished, upload your source code to Canvas.

Wrap Up
  • With your partner, answer the questions from today's learning objectives

Upcoming Assignments