Thread: Point Drill Program - Help Needed

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

    Point Drill Program - Help Needed

    I'm having trouble with a program that requires a data-type Point with coordinates x and y (which are ints). Input from one file and output to another file, like the other File stream program I had to do.

    The specs are like this:
    1. Start a program to work with points, discussed in 10.4. Begin by defining the data type Point that has two coordinate members x and y.
    2. Using the code and discussion in 10.4, prompt the user to input seven (x,y) pairs. As the data is entered, store it in a vector of Points called original_points.
    3. Print the data in original_points to see what it looks like.
    4. Open an ofstream and output each point to a file named mydata.txt. On Windows, we suggest the .txt suffix to make it easier to look at the data with an ordinary text editor (such as WordPad).
    5. Close the ofstream and then open an ifstream for mydata.txt. Read the data from mydata.txt and store it in a new vector called processed_points.
    6. Print the data elements from both vectors.
    7. Compare the two vectors and print Something's wrong! if the number of elements or the values of elements differ.
    As for Section 10.4 in the book that this is referring to, here:
    Code:
    cout << "Please enter input file name: ";
     string iname;
     cin >> iname;
     ifstream ist {iname};          // ist is an input stream for the file named name
     if (!ist) error("can't open input file ",iname);

    Defining an ifstream with a name string opens the file of that name for reading. The test of !ist checks if the file was properly opened. After that, we can read from the file exactly as we would from any other istream. For example, assuming that the input operator, >>, was defined for a type Point, we could write


    Code:
    vector<Point> points;
     for (Point p; ist>>p; )
               points.push_back(p);
    Output to files is handled in a similar fashion by ofstreams. For example:
    Click here to view code image
    Code:
    cout << "Please enter name of output file: ";
     string oname;
     cin >> oname;
     ofstream ost {oname};           // ost is an output stream for a file named oname
     if (!ost) error("can't open output file ",oname);

    Defining an ofstream with a name string opens the file with that name for writing. The test of !ost checks if the file was properly opened. After that, we can write to the file exactly as we would to any other ostream. For example:
    Click here to view code image
    Code:
    for (int p : points)
               ost << '(' << p.x << ',' << p.y << ")\n";

    When a file stream goes out of scope its associated file is closed. When a file is closed its associated buffer is “flushed”; that is, the characters from the buffer are written to the file.
    It is usually best to open files early in a program before any serious computation has taken place. After all, it is a waste to do a lot of work just to find that we can’t complete it because we don’t have anywhere to write our results.
    Opening the file implicitly as part of the creation of an ostream or an istream and relying on the scope of the stream to take care of closing the file is the ideal. For example:
    Click here to view code image
    Code:
     void fill_from_file(vector<Point>& points, string& name)
     {
               ifstream ist {name};           // open file for reading
               if (!ist) error("can't open input file ",name);
               // . . . use ist . . .
               // the file is implicitly closed when we leave the function
     }
    You can also perform explicit open() and close() operations (B.7.1). However, relying on scope minimizes the chances of someone trying to use a file stream before it has been attached to a stream or after it was closed. For example:
    Click here to view code image
    Code:
    ifstream ifs;
     // . . .
     ifs >> foo;                                            // won’t succeed: no file opened for ifs
     // . . .
     ifs.open(name,ios_base::in);         // open file named name for reading
     // . . .
     ifs.close();                                           // close file
     // . . .
     ifs >> bar;                                           // won’t succeed: ifs’ file was closed
     // . . .

    In real-world code the problems would typically be much harder to spot. Fortunately, you can’t open a file stream a second time without first closing it. For example:
    Click here to view code image
    Code:
     fstream fs;
     fs.open("foo", ios_base::in) ;         // open for input
     // close() missing
     fs.open("foo", ios_base::out);      // won’t succeed: fs is already open
     if (!fs) error("impossible");
    Don’t forget to test a stream after opening it.
    Why would you use open() or close() explicitly? Well, occasionally the lifetime of a connection to a file isn’t conveniently limited by a scope so you have to. But that’s rare enough for us not to have to worry about it here. More to the point, you’ll find such use in code written by people using styles from languages and libraries that don’t have the scoped idiom used by iostreams (and the rest of the C++ standard library).
    As we’ll see in Chapter 11, there is much more to files, but for now we know enough to use them as a data source and a destination for data. That’ll allow us to write programs that would be unrealistic if we assumed that a user had to directly type in all the input. From a programmer’s point of view, a great advantage of a file is that you can repeatedly read it during debugging until your program works correctly.
    Here's my code:
    Code:
    #include "../custom_std_lib_facilities.h"
    #include <fstream>
    #include <vector>
    
    using namespace std;
    
    struct Point
    {
        int x;
        int y;
    };
    
    bool is_file_valid(const string& iname, const ifstream& ist);
    
    istream& operator>>(istream& is, const Point& point);
    
    vector<Point>& read_coordinates(ifstream& ist, vector<Point>& original_points);
    
    int main()
    {
        try
        {
            string iname;
            cout << "Please enter name of input file: ";
            cin >> iname;
            ifstream ist{iname};
            if (!ist)
            {
                error("error: can't open file", iname);
            }
            vector<Point> original_points;
            int count;
            for (Point point; ist >> point;)
            {
                original_points.push_back(point);
                count++;
                if (count == 7)
                {
                    break;
                }
            }
        }
        catch(runtime_error& r)
        {
            cout << r.what() << "\n";
            keep_window_open();
            return 1;
        }
        catch(...)
        {
            cout << "Error: Unknown exception! Please try again later.\n";
            keep_window_open();
            return 2;
        }
    }
    
    istream& operator>>(istream& is, const Point& point)
    {
        is >> point;
        return is;
    }
    It compiles and links just fine, but when I run it, it crashes right after taking in the input file name. Error 255. What could I have done to make this happen?
    Last edited by Osman Zakir; 07-11-2015 at 06:53 PM.

  2. #2
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Start with finishing your other exercise(s) first. Seriously. You're not going to learn at this rate. You need to get down the basics and understand what you're doing, but if you just continue to do exercises without understanding the former ones first, you're going to get information overload.
    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.

  3. #3
    Registered User
    Join Date
    Mar 2015
    Posts
    184
    You can't build a house on marsh land.

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Quote Originally Posted by jiggunjer View Post
    You can't build a house on marsh land.
    Good analogy, related to a strangely relevant quote.

    "Other kings said I was daft to build a castle on a swamp, but I built it all the same, just to show 'em. It sank into the swamp.
    So, I built a second one. That sank into the swamp.
    So I built a third one. That burned down, fell over, then sank into the swamp.
    But the fourth one... stayed up!"

  5. #5
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    The problem here seems to be that it's crashing after taking in the input for the file name. Is it a segmentation fault?

  6. #6
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    I tried to fix it and now it just freezes up when trying to read from the input file. I seem to be almost done with the Book class code, so I'll copy-post the code for this one here again:
    Code:
    #include "../custom_std_lib_facilities.h"
    #include <fstream>
    #include <vector>
    
    using namespace std;
    
    struct Point
    {
        int x;
        int y;
    };
    
    bool is_file_valid(const string& iname, const ifstream& ist);
    
    istream& operator>>(istream& is, Point& point);
    
    ostream& operator<<(ostream& os, Point& point);
    
    vector<Point>& read_coordinates(ifstream& ist, vector<Point>& original_points);
    
    int main()
    {
        try
        {
            string iname;
            cout << "Please enter name of input file: ";
            cin >> iname;
            ifstream ist{iname};
            if (!ist)
            {
                error("error: can't open file", iname);
            }
            vector<Point> original_points;
            Point point;
            for (ist >> point;;)
            {
                original_points.push_back(point);
            }
            string oname;
            cout << "Please enter name of output file: ";
            cin >> oname;
            ofstream ost{oname};
            if (!ost)
            {
                error("error: can't open output file", oname);
            }
            for (size_t i = 0; i < original_points.size(); i++)
            {
                ost << "(" << point.x << ", " << point.y << ")\n";
            }
        }
        catch(runtime_error& r)
        {
            cout << r.what() << "\n";
            keep_window_open();
            return 1;
        }
        catch(...)
        {
            cout << "Error: Unknown exception! Please try again later.\n";
            keep_window_open();
            return 2;
        }
    }
    
    istream& operator>>(istream& is, Point& point)
    {
        return is >> point.x >> point.y;
    }
    
    ostream& operator<<(ostream& os, Point& point)
    {
        return os << point.x << point.y;
    }

  7. #7
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Osman Zakir View Post
    I seem to be almost done with the Book class code...
    Far from it.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Book Drill Question Help Needed
    By Osman Zakir in forum C++ Programming
    Replies: 1
    Last Post: 04-16-2015, 09:33 PM
  2. Replies: 1
    Last Post: 01-21-2013, 07:15 AM
  3. Replies: 6
    Last Post: 07-14-2012, 09:43 AM
  4. Bug in the addition drill program
    By Sharifhs in forum C Programming
    Replies: 1
    Last Post: 08-13-2010, 10:50 PM
  5. help needed in floating point
    By akshayabc in forum C Programming
    Replies: 5
    Last Post: 06-27-2005, 11:00 AM