Search code examples
c++arraysmultidimensional-arrayifstreamofstream

C++ Multi-Dimensional Array saving/loading to file error


I've been working on this C++ project for roughly 2 weeks now and I'm stumped on a couple things regarding 2D Arrays. To start off here is the code I wrote as of now:

http://pastebin.com/vCsz947Q

I decided to provide this as a pastebin link due to the fact that it's rather large (it uses 8 functions) and I thought it would save space in this post. I'm new to this site so I apologize if there's a better way that I'm not aware of.

The Problem:

When I go to save my "char seating" array to a .dat file using the "save seats" function that I created, I get a file that gives me the following garbage character " Ì " instead of the intended ' # ' (for open seats) or ' * ' (if a seat is bought).

My functions will save the intended amount of rows (15) and columns (30) despite this though. Also an asterisk will be placed when I go to "purchase a seat" in this program in the file. Additionally my program loads the files as intended, except for the fact that... Well... There's garbage data stored in the seat array.

I feel like this relates to another problem I'm having where if I go to the "purchase seats" function and I say to purchase a seat, it should replace a # with a *, but it doesn't, yet in the saved file it will show an asterisk in the intended spot... Which is very strange.

I have absolutely no idea why this occurs, and what's frustrating is this one thing that's preventing me from finishing this program. I want to believe that my original array in int main that's being called by other functions isn't being updated properly, but I don't know, which is why I came here to seek assistance.

Thank you for your assistance whoever can help.


Solution

  • Well for a start you have some undefined behaviour here inside your displaySeatingChart (char displaySeats[ ][30], float displayPrices[ ]) function with the following:

    const int rowDisplay = 15;
    const int colDisplay = 30;
    

    as later within one of your loops you have

    cout << displaySeats[rowDisplay][colDisplay];
    

    which is clearly reading beyond the array bounds since in main() you define

    const int rowMain = 15;
    const int colMain = 30;
    char seating[rowMain][colMain];
    float seatPrices[15];
    

    and pass both seating and seatPrices to the displaySeats function. There may well be other problems with your code but this at least is a clear example of undefined behaviour. Consider stepping through the code with a debugger to get a clearer idea of the source of the issue.

    On another note given that you are working with C++ consider working with std::vector instead of arrays. This will give you more scope to ascertain the dimensions of the items that arrays that you are working with from within your utility functions and result in less potential for errors in array access.