-3

I am new to using C++ and Microsoft Visual Studio and I trying to convert a data file (2 columns by 500 rows consisting of floats) into an array, and then I am trying to output the array on screen. Whenever I try to run it, it comes up with "Unhandled exception at 0x001BC864 in file.exe: 0xC0000005: Access violation writing location 0x00320A20."
I found this video and tried to adapt that code https://www.youtube.com/watch?v=4nz6rPzVm70 Any help would be appreciated.

#include<stdio.h>
#include<string>
#include<iostream> // 
#include<fstream> // 
#include<array> // 
#include<iomanip> //
#include<sstream>//
#include<conio.h>
using namespace std;

int rowA = 0; // 
int colA = 0;


int main()
{
string lineA; 
int x;
float arrayA[2][500] = { { 0 } }; 
ifstream myfile("C:/results.dat"); 
if (myfile.fail()) {
    cerr << "File you are trying to access cannot be found or opened";
    exit(1);
}

    while (myfile.good()) { 
    while (getline(myfile, lineA)) {
        istringstream streamA(lineA);
        colA = 0; 
        while (streamA >> x) { 
            arrayA[rowA][colA] = x; 
            colA++;             }
        rowA++;         }
}


cout << "# of Rows --->" << rowA << endl; 
cout << "# of Columns --->" << colA << endl; 
cout << " " << endl;
for (int i = 0; i < rowA; i++) {
    for (int j = 0; j < colA; j++) {
        cout << left << setw(6) << arrayA[i][j] << " ";
    }
    cout << endl;
}

return 0;
_getch();
 }
Yirkha
  • 12,737
  • 5
  • 38
  • 53
Student201
  • 143
  • 8
  • If you have 500 lines of two floats each, then `float arrayA[2][500]` and `arrayA[rowA][colA]` don't go well together. They would if you had 2 lines of 500 floats. – Wintermute Apr 02 '15 at 15:04
  • Ok thank you, do you have a suggestion of what I could do instead please? – Student201 Apr 02 '15 at 15:06
  • 3
    This question is not specific to Visual studio. It is a generic c++ question. You having trouble with c++ arrays is what the question is about. The first step to master programming is to be able to pin down the source of a problem. – BitTickler Apr 02 '15 at 15:09
  • try [here][1] for floats or [here][2] for ints [1]: http://stackoverflow.com/questions/8421170/read-floats-from-a-txt-file [2]: http://stackoverflow.com/questions/8116808/read-integers-from-a-text-file-with-c-ifstream – user3443369 Apr 02 '15 at 15:12
  • `float arrayA[500][2]` might solve the problem for this particular file. More generally, take a look at [`std::vector`](http://en.cppreference.com/w/cpp/container/vector), where the number of elements does not have to be known at compile time (and can be adjusted at runtime), and know that you can have a `std::vector>`. This is about as much of a suggestion as I can give without any knowledge of the meaning and structure of the data you're reading. – Wintermute Apr 02 '15 at 15:17
  • Thanks for your suggestions, it is all working now thanks. – Student201 Apr 02 '15 at 18:29

1 Answers1

2

Obviously your access to the array is out of bounds as you have your array indices go beyond the size of the array dimensions.

Given that this will not be the last time you run into this kind of problems, my answer will give you tips on how to detect if stuff like that goes wrong.

Your first tool on the rack is to add assertions to your code which make the problem evident in a debug build of your code.

 #include <cassert>

 // ...
 while (myfile.good()) { 
 while (getline(myfile, lineA)) {
    istringstream streamA(lineA);
    colA = 0; 
    while (streamA >> x) { 
        // probably you would have noticed the error below while writing 
        // those assertions as obviously you would notice that you want 500
        // rows and not 2 and you want 2 columns, not 500...
        assert( rowA < 2 ); // <<--- This will assert!
        assert( colA < 500 ); // <<--- This will assert if there are more than 500 lines in the file.
        arrayA[rowA][colA] = x; 
        colA++;             }
    rowA++;         }

With only those 2 extra lines (and the include), you would have been able to see where your code messes up.

In this case, fixing your code is quite easy and I leave it to you as an exercise ;)

In order to avoid mixing up the indices for your multi-dimensional array, you could write your code in a more suggestive manner (more readable).

int main()
{
    string lineA; 
    int x;
    const int NUM_COLUMNS = 2;
    const int NUM_ROWS = 500;
    float arrayA[NUM_COLUMNS][NUM_ROWS] = { { 0 } }; 
    // ...

This tiny bit of extra expressiveness increases your odds to notice that your array access further below uses the wrong index variables per array dimension.

Last not least, you should add extra checks given that your program only works correctly (after fixing it) if the input file does not violate your assumptions (2 columns, less than 501 rows). This falls under the chapter of "defensive programming" - i.e. your code protects itself from violations of assumptions outside its scope of control.

You repeat your error in the print-loop at the bottom, btw. There, too you could add assertions.

BitTickler
  • 10,905
  • 5
  • 32
  • 53