0

I am trying to read a csv file and store it as an array.

I created the csv in python using pandas like this:

x = df['green'][:10]
x.to_csv('sample_green.csv', index=False, header=True)

When I cat the file in my terminal, it looks like this:

green
84.6974
84.6737
84.636
84.728
84.7692
84.7661
84.7764
84.758
84.7469
85.1841

I am trying to read it into my file with this code:

    // define variables
    string green; //variables from file are here
    vector<float>g;

    //input filename
    string file;
    cout << "Enter the filename: ";
    cin >> file;
    cout << file << endl;

    //number of lines
    int i = 0;

    ifstream coeff(file); //opening the file.
    if (coeff.is_open()) //if the file is open
    {
        //ignore first line
        string line;
        getline(coeff, line);

        while (!coeff.eof()) //while the end of file is NOT reached
        {
            //I have 4 sets {alpha, CD, CL, CY} so use 4 getlines
            getline(coeff, green, '\n');
            g.push_back(stof(green));
            
            i += 1; //increment number of lines
        }
        coeff.close(); //closing the file
        cout << "Number of entries: " << i-1 << endl;
    }
    else cout << "Unable to open file" <<endl; //if the file is not open output

When I run my program, I am prompted to enter the filename like this:

Enter the filename:

Where I enter sample_green.csv, which is in the same directory.

I keep getting this error. I made sure there are no NaN values in my csv. What is going on?

sample_green.csv
libc++abi.dylib: terminating with uncaught exception of type std::invalid_argument: stof: no conversion
Abort trap: 6

Eventually, the array I read in will be used in place of this example arr in my code below:

    nc::array sample;
    double arr [] = {200,210,300,250,400,500,550,780,1100,321,200,350,400,430,489,424,612,732,770,900,1400,1802,532,402,423};
    for(int i=0;i<(sizeof(arr)/sizeof(arr[0]));i++) {
        sample.push_back(arr[i]);
    }
connor449
  • 791
  • 4
  • 19
  • 1
    You should read: [Why is `iostream::eof()` inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons). TL;DR: Use `while(getline(coeff, green)) { g.push_back(stof(green)); }` instead. – Ted Lyngmo Jan 28 '21 at 17:02

0 Answers0