c++ gives Segmentation Fault from text file of all 0's

81 Views Asked by At

I'm writing a really simple code (or so I thought) that requires 2 text files to be read in. One is full of a bunch of data points (of type double) and the other one happens to be a bunch of 0's (this is only SOMETIMES filled with 0's, sometimes it will be other numbers, so I need it to work for both 0's and non-zero's) like so:

0
0
0
..

I am reading these into vectors like so:

vector <double> E;
vector <double> M;
ifstream Ein("E.txt");
ifstream Min("M.txt");

while ( Ein >> value ) {
        E.push_back(value);
    }

     while ( Ein >> value ) {
        M.push_back(value);
    }

This works perfectly for the vector E (the one with actual values) after I comment out the M vector. But whenever I include the M vector (all 0's) I get a segmentation fault when I run the program.

This means that C++ doesn't understand 0 as an input I guess? Does anyone have any ideas on how to get this to work?

Thanks in advance!

2

There are 2 best solutions below

1
On BEST ANSWER

For the second while loop, did you want to have:

while ( Min >> value ) {
   M.push_back(value);
}

You're getting the segmentation fault because the Ein has hit EOF. Also, you may want to close the input streams :)

1
On

You should make sure that you close the file stream, you're also reading from the same file twice, which is why you're getting the seg fault