Previous Lecture lect07 Next Lecture

lect07, Tue 04/23

Midterm preparation and overview / Reading from files

Code from Lecture

Introducing ifstream object.

// main.cpp
// Testing ifstream with >> and getline
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    ifstream ifs;
    string my_line;

    ifs.open("test.txt");
    ifs >> my_line;
    cout << my_line << endl;

    getline(ifs, my_line);
    cout << my_line << endl;

    ifs >> my_line;
    cout << my_line << endl;

    return 0;
}

Expanded example, using a while loop:

/// io.cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    ifstream ifs;
    string my_line;

    ifs.open("test.txt");
    if (ifs.fail())
    {
        cerr << "Unable to open the file" << endl;
        exit(-1);
    }

    while (getline(ifs, my_line))
    {
        cout << my_line << endl;
        if (my_line == "line1")
        {
            cout << "Hello, line1" << endl;
        }

    }

    ifs.close();
    cout << "The End" << endl;

    return 0;
}

Contents of test.txt line1 line 2 line 3 and 4

Midterm preparation

See the lecture slides for the list of topics on the exam, as well as the practice problems and solutions presented during lecture.

Here are some problems to expect:

Note that this list is not comprehensive, and you should be comfortable with any material discussed in lectures, homeworks, and labs.

Converting the example from the slides to accept the user input from the command line. Note that the program will crash if no additional command-line arguments (other than the name of the executable) are provided!

// mult_cl.cpp
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    int sum = 0;
    int n = -1;

    n = atoi(argv[1]);

    for(int i = 1; i < n; i++)
    {
        if ((i % 3 == 0) || (i % 5 == 0))
        {
            sum += i;
        }
    }
    cout << "The sum is " << sum << endl;
    return 0;
}

Miscellaneous


Converting the example from the slides to use a function and provide a more elaborate output:

// mult_funct_n.cpp
#include <iostream>
using namespace std;

int compute_sum(int limit)
{
    int sum = 0;

	for(int i = 1; i < limit; i++)
	{
		if ((i % 3 == 0) || (i % 5 == 0))
		{
			sum += i;
		}
	}

    return sum;
}

int main()
{
   int n = -1;
	cout << "Enter n: ";
	cin >> n;

    for (int i = 0; i < n; i++)
    {
        cout <<"i = " << i << " The sum is " << compute_sum(i) << endl;
    }
	return 0;
}

Practice Questions

  1. What’s another way to read input from an ifstream object, apart from using >>? Assume we have an ifstream object named ifs, and a string object named my_line.
  2. What is the output of the following code? Assume it’s integrated as part of a working C++ program.
    bool x = 129;
    bool y = false;
    cout << x << endl;
    cout << y << endl;