Thread: File_stream Practice Program

  1. #1
    Registered User
    Join Date
    Mar 2015
    Posts
    384

    File_stream Practice Program

    I tried to compile an example code from the book I'm reading:
    Code:
    #include "../custom_std_lib_facilities.h"
    #include <vector>
    #include <fstream>
    
    using namespace std;
    
    struct Reading      // a temperature reading
    {
        int hour;       // hour after midnight [0:23]
        double temperature;     // in Fahrenheit
    };
    
    int main()
    {
        cout << "Please enter input file name: ";
        string iname;
        cin >> iname;
        ifstream ist {iname};      // ist reads from the file named iname
        try
        {
            if (!ist)
            {
                error("can't open input file ", iname);
            }
        }
        catch (runtime_error& r)
        {
            cout << r.what() << "\n";
            keep_window_open();
            return 1;
        }
        catch(exception& e)
        {
            cout << e.what() << "\n";
            keep_window_open();
            return 2;
        }
        catch(...)
        {
            cout << "Whoops! Unknown exception! Please try again later.\n";
            keep_window_open();
            return 3;
        }
        string oname;
        cout << "Please enter name of output file: ";
        cin >> oname;
        ofstream ost {oname};       // ost writes to a file named oname
        try
        {
            if (!ost)
            {
                error("can't open output file ", oname);
            }
        }
        catch (runtime_error& r)
        {
            cout << r.what() << "\n";
            keep_window_open();
            return 1;
        }
        catch (exception& e)
        {
            cout << e.what() << "\n";
            keep_window_open();
            return 2;
        }
        catch(...)
        {
            cout << "Whoops! Unknown exception! Please try again later.\n";
            keep_window_open();
            return 3;
        }
        vector<Reading> temps;
        int hour;
        double temperature;
        try
        {
            while (ist >> hour >> temperature)
            {
                if (hour < 0 || hour > 23)
                {
                    error("hour out of range (should be in range 0 to 23)");
                }
                temps.push_back(Reading{hour, temperature});
            }
        }
        catch(runtime_error& r)
        {
            cout << r.what() << "\n";
            keep_window_open();
            return 1;
        }
        catch(exception& e)
        {
            cout << e.what() << "\n";
            keep_window_open();
            return 2;
        }
        catch(...)
        {
            cout << "Whoops! Unknown exception! Please try again later.\n";
            keep_window_open();
            return 3;
        }
        for (size_t i = 0; i < temps.size(); i++)
        {
            ost << "(" << temps[i].hour << ";" << temps[i].temperature << "\n";
        }
        keep_window_open();
    }
    It just executes keep_window_open() after reading in the names of both files (iname and oname).

    Note: This is the header Stroustrup has been using in the book so far (click the link, please): http://www.stroustrup.com/Programmin...b_facilities.h.

    It says we are to use this for the first few weeks only, but I didn't want to take chances and actually wanted to use the actual header files themselves and learn about them, so I made up my own custom_std_lib_facilities.h since I also didn't want to clutter my program's object code with header files I didn't need (that and I'd rather "use namespace std" on my own, rather than through a header that has that "using" line in it already (which std_lib_facilities.h does)).

  2. #2
    Unregistered User Yarin's Avatar
    Join Date
    Jul 2007
    Posts
    2,158
    I'd have a hard time trusting a C++ book with example code that doesn't return from a non-void function. If that's really the code from the book as-is, you should let your educator know.

  3. #3
    Guest
    Guest
    So what names have you chosen for you input and output files? Does the program create an output file? What is its content? "It doesn't work." is not the right attitude, "I better find out!" is.

    Quote Originally Posted by Yarin View Post
    I'd have a hard time trusting a C++ book with example code that doesn't return from a non-void function. If that's really the code from the book as-is, you should let your educator know.
    Stroustoup seems very sloppy (insert joke about C++ here). I got pretty frustrated finding so many errors in his book. He should be teaching me, the learner, not vice versa.
    Last edited by Guest; 06-30-2015 at 03:51 PM.

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    You don't need to return from main. The standard says it implicitly returns 0 if you don't.
    As for why it's not working, ensure that the input file you input exists and that you can read it and that it contains an int and a double.

    Example: 10 20.0
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #5
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    I'm making sure to only input names of files I know exist. Although they're files I've created and added to the project folder that the program is in (it's part of the project tree).

    I've got two .cpp files in the folder besides the main one, "temp_reading_file.cpp" and "temp_reading_outputfile.cpp". I enter the name of the former as the input file name and the latter as the output file name. It accepts the input, but then it goes straight to executing keep_window_open() rather than continuing on down to the while-loop that reads from my ifstream ist.

  6. #6
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I echo what I mentioned in my last reply. Make sure the files exist and that the path is correct. To rule out that it's not a path issue, enter the absolute path to these files.
    Then make sure the input file contains the right format. It should be an int, then a double, then repeat that pattern. If you ensure that, it works. I tested.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #7
    Guest
    Guest
    What is the current content of your input file? To debug things, you could start by printing hour and temperature as they come out of the ifstream, instead of pushing them into the vector.

    Quote Originally Posted by Osman Zakir View Post
    I've got two .cpp files in the folder besides the main one, "temp_reading_file.cpp" and "temp_reading_outputfile.cpp". I enter the name of the former as the input file name and the latter as the output file name.
    I would strongly suggest you use a different file extension (like .txt). You're not storing code in those, so that's pretty confusing

  8. #8
    Unregistered User Yarin's Avatar
    Join Date
    Jul 2007
    Posts
    2,158
    Quote Originally Posted by Guest View Post
    Stroustoup seems very sloppy (insert joke about C++ here). I got pretty frustrated finding so many errors in his book. He should be teaching me, the learner, not vice versa.
    Is that really Stroustoup's code? Well then, who am I to argue with the creator, even if it is, as you rightly point out, sloppy.

    I swear, every time I learn something new about C++, it makes me that much more glad that I don't see much C++ in my future.

  9. #9
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    It's just that Stroustrup's coding style is a bit compact. Not much whitespace (at least, not as much as I'd like to leave).
    And as Elysia said, main() returns 0 by default, so you don't really need to explicitly do it. The only time you have to include a return statement in main() is when you want to return a number other than 0 (to indicate an error).

    And by the way, this is Stroustrup's original code (it uses std_lib_facilities.h which I posted a link to in this thread):
    Code:
    #include "std_lib_facilities.h"
     
     struct Reading {                                  // a temperature reading
               int hour;                                    // hour after midnight [0:23]
    double temperature;             // in Fahrenheit
     };
     
     int main()
     {
               cout << "Please enter input file name: ";
               string iname;
               cin >> iname;
               ifstream ist {iname};               // ist reads from the file named iname
               if (!ist) error("can't open input file ",iname);
     
               string oname;
               cout << "Please enter name of output file: ";
               cin >> oname;
               ofstream ost {oname};           // ost writes to a file named oname
               if (!ost) error("can't open output file ",oname);
     
               vector<Reading> temps;      // store the readings here
               int hour;
               double temperature;
               while (ist >> hour >> temperature) {
                         if (hour < 0 || 23 <hour) error("hour out of range");
                         temps.push_back(Reading{hour,temperature});
               }
     
               for (int i=0; i<temps.size(); ++i)
                         ost << '(' << temps[i].hour << ','
                                   << temps[i].temperature << ")\n";
     }
    Different from my coding style, especially in how he likes to put the code for an if-block on the same line as the condition there's only one small line of code.

    The error code in my if-conditions should execute if something goes wrong while trying to open a file for reading or writing, right? The fact that nothing goes wrong should mean that the file exists and that the program manages to find it. So it should be that I need to make a .txt file. A .docx caused it to run the code in error().

    Edit: Just now, I tried inputting the file with its path and it still had the same result as before (I did "C:\Users\Osman\Documents\temp_reading_inputfile.t xt" and "C:\Users\Osman\Documents\temp_reading_outputfile. txt").

    Edit2: Why is the file extension part not coming out right in this?
    Last edited by Osman Zakir; 06-30-2015 at 05:42 PM.

  10. #10
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    For Edit) There are spaces in your name, e.g. "t xt". They obviously shouldn't be there, but I don't know if it is a bug when you copied your path to the board.
    For Edit2) No idea what that even means.

    Tell you what. Reverse your input/output code so you write first, then read. Then specify the same filename for the input and output filenames. Be sure you CLOSE your output file before opening it for reading.

    So input input, output filenames.
    Open file for writing.
    Write data.
    Close file.

    Open file for reading.
    Read data.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #11
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    It put spaces in there when I copy-pasted it here. That's also what I meant in Edit2.

    Anyway, do you mean should put the code from the declaration of the vector temps and everything after that first, and then the rest of the code after it?

  12. #12
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Code:
    #include "std_lib_facilities.h"
      
    struct Reading
    {                                  // a temperature reading
        int hour;                                    // hour after midnight [0:23]
        double temperature;             // in Fahrenheit
    };
      
    int main()
    {
               cout << "Please enter input file name: ";
               string iname;
               cin >> iname;
               if (!ist) error("can't open input file ",iname);
      
               string oname;
               cout << "Please enter name of output file: ";
               cin >> oname;
               if (!ost) error("can't open output file ",oname);
      
               ofstream ost {oname};           // ost writes to a file named oname
               for (int i=0; i<temps.size(); ++i)
                         ost << '(' << temps[i].hour << ','
                                   << temps[i].temperature << ")\n";
    ost.close();
    
               ifstream ist {iname};               // ist reads from the file named iname
               vector<Reading> temps;      // store the readings here
               int hour;
               double temperature;
               while (ist >> hour >> temperature) {
                         if (hour < 0 || 23 <hour) error("hour out of range");
                         temps.push_back(Reading{hour,temperature});
               }
      
    // Print inputs here if you want to verify it worked correctly. You may also want to change the variables so you can see if they values actually changed or not.
     }
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  13. #13
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    I ran the code after changing it to this:
    Code:
    #include "../custom_std_lib_facilities.h"
    #include <vector>
    #include <fstream>
    #include <sstream>
    
    using namespace std;
    
    struct Reading      // a temperature reading
    {
        int hour;       // hour after midnight [0:23]
        double temperature;     // in Fahrenheit
    };
    
    int main()
    {
        cout << "Please enter input file name: ";
        string iname;
        cin >> iname;
        ifstream ist {iname};       // ist reads from the file named iname
        if (!ist)
        {
            error("can't open input file ",iname);
        }
        string oname;
        cout << "Please enter name of output file: ";
        cin >> oname;
        ofstream ost {oname};       // ost writes to a file named oname
        if (!ost)
        {
            error("can't open output file ",oname);
        }
        vector<Reading> temps;      // store the readings here
        for (size_t i = 0; i < temps.size(); i++)
        {
            ost << '(' << temps[i].hour << ',' << temps[i].temperature << ")\n";
        }
        ost.close();
        int hour;
        double temperature;
        while (ist >> hour >> temperature)
        {
            if (hour < 0 || hour > 23)
            {
                error("hour out of range");
            }
            temps.push_back(Reading{hour,temperature});
        }
        keep_window_open();
    }
    And then when I went to my Documents folder and opened those files, I found that they were empty.

  14. #14
    Guest
    Guest
    So what do you get when printing (to the console) the values coming from the ifstream?

  15. #15
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Several questions:

    1. What does your input file contain prior to running the program?

    2. If it does contain information, where do you read the information? Where do you try to write the information?

    3. Why are you surprised that your output file is empty? Since you haven't yet read the input file there is nothing to print, your vector is empty.

    Jim

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Chapter 5 practice program 2 difficulties
    By DaveHubbard in forum C++ Programming
    Replies: 15
    Last Post: 05-17-2013, 01:24 PM
  2. Best practice for super simple program
    By samwillc in forum C++ Programming
    Replies: 10
    Last Post: 06-02-2012, 04:29 PM
  3. Boat loader my practice program
    By jimtuv in forum C Programming
    Replies: 10
    Last Post: 05-29-2010, 09:43 PM
  4. help on this very small practice program
    By incognito in forum C++ Programming
    Replies: 4
    Last Post: 01-01-2002, 10:28 AM