Search code examples
c++vectorfilestreamifstream

C++: Input file (data of unknown size) into vector issue


I'm trying to put a file with two columns of data, x and y, into two vectors, one only containing x and the other only containing y. No column headers. Like this:

x1 y1
x2 y2
x3 y3

However, when I run this code, I encounter an error: (lldb) Can someone tell me if I'm doing anything wrong?

#include <iostream>
#include <cmath> 
#include <vector>
#include <fstream> 

using namespace std;

int main() {

    vector <double> x; 
    vector <double> y; 

    ifstream fileIn;

    fileIn.open("data.txt"); //note this program should work for a file in the above specified format of two columns x and y, of any length.

    double number;

    int i=0;

    while (!fileIn.eof())
    {
        fileIn >> number;
        if (i%2 == 0) //while i = even
        {
            x.push_back(number); 
        }
        if (i%2 != 0) 
        {
            y.push_back(number); 
        }
        i++; 
    }
    cout << x.size();
    cout << y.size();

    fileIn.close();
    return 0;
}

Solution

  • If the file data.txt cannot be opened, the program enters in an infinite loop, and if you kill it (with Ctrl+C), the message "lldb" is the debugger's name. You should write something like:

    fileIn.open("data.txt"); //note this program ...
    if(!fileIn) { // check if fileIn was opened
        cout << "error opening data.txt\n";
        return 1;
    }
    

    and see. Also,

    while (!fileIn.eof())

    is not the correct way for reading your file. See: Reading a C file, read an extra line, why?