Bjarne Stroustrup chapter 10.5 example

327 views Asked by At

This is about an example in Section 10.5 of Bjarne Stroustrup's "Principles and Practices using C++" book. As far as I understand, it should prompt the user to enter the name of the file to be created (So I typed probe.txt), after that it should ask the user to open a file (So I type probe.txt again) and then the program skips my while statement and returns 0. How am I supposed to enter the hours and temperatures?

#include <std_lib_facilities.h>

struct Reading {
    int hour;
    double temperature;
};

int main()
{
    cout << "Please enter input file name: \n";
    string iname;
    cin >> iname;
    ifstream ist{iname};

    string oname;
    cout << "Please enter output file name: \n";
    cin >> oname;
    ofstream ost{oname};

    vector<Reading> temps;
    int hour;
    double temperature;
    while (ist >> hour >> temperature) {
        temps.push_back(Reading{hour,temperature});
    }

    keep_window_open();
    return 0;
}
1

There are 1 answers

1
sitting-duck On

When you see the prompt:

cout << "Please enter input file name: \n";

It is asking you what file you want to read the data from.

When you see the prompt:

cout << "Please enter output file name: \n";

It is asking you what file you want to write to.

Notice the difference in the key words input and output.

This loop:

while (ist >> hour >> temperature) {
            temps.push_back(Reading{hour,temperature});

Is saying that while ist (the input file stream) returns a good value (meaning it hasn't reached the end of file yet) we add an item of type Reading to the Vector called "temps". (A Vector is essentially a list container type) We created an item of type Reading from the two items we grabbed from the line in the file.

So to recap, we make a Reading from the text in the file, and then we add it to the vector called "temps"

">>" is an operator that reads the next item in the file. In the code, it reads the next two items and puts them into hour and temperature.