0

This is the code I'm using to attempt to read two columns of data from a csv file into a vector in C++. I'm able to read in the headers, but when i continue into reading the actual data I'm getting an error involing 'stof', which converts string to float. I'm pretty sure that this error results from stof not being able to find any amount of string to convert to a float, but this makes no sense as the variable inside the parenthesis is indeed a string, that is holding digits.

#include <vector>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>

using namespace std;

int main(int argc, char** argv)
{


    ifstream inFS;
    string line;
    string rm_in, medv_in;
    const int MAX_LEN = 1000;
    vector<double> rm(MAX_LEN);
    vector<double> medv(MAX_LEN);

    cout << "Opening file MyData.csv" << endl;

    inFS.open("MyData.csv");
    if(!inFS.is_open())
    {
        cout << "Could not open file MyData.csv" << endl;
        return 1;
    }

    cout << "Reading line 1" << endl;
    getline(inFS, line);

    cout << "heading :" << line << endl;

    int numObservations = 0;
    while(inFS.good())
    {
        getline(inFS, rm_in , ',');
        getline(inFS, medv_in , '\n');
        rm.at(numObservations) = stof(rm_in);
        medv.at(numObservations) = stof(medv_in);
        numObservations++;
    }
    rm.resize(numObservations);
    medv.resize(numObservations);

}

The error I'm getting is this: error

  • 1
    Judged by only reading the error message, **the argument** which got passed into the function **`stof()`**, is invalid. Maybe check it first :) – Uduru Jun 08 '21 at 02:39
  • Step one: You should investigate the contents of `rm_in` and `medv_in` right before they're passed to `stof`. Use a debugger or just `cout` the data at that point. There's a good chance you'll find an obvious problem you can fix. – TheUndeadFish Jun 08 '21 at 02:42
  • When I cout the contents of rm_in I get the values within the csv file like this: 1982.2982.2982. I'm unsure what to do with this information. It seems to me like the numbers within rm_in are already not string? But the variable itself is a string. I'm confused if you can't tell. – berkleybaby Jun 08 '21 at 02:55
  • [Why !.eof() inside a loop condition is always wrong.](https://stackoverflow.com/q/5605125/9254539) That is simply the inverse of `while(inFS.good())`. It will be good at the test, but at the end of the file, `getline(inFS, rm_in , ',');` will trigger `inFS.eof()` which goes uncaught and you then attempt to use `rm_in` and `medv_in` thereafter. Instead `while (getline(inFS, rm_in , ',') && getline(inFS, medv_in , '\n')) { ... }` – David C. Rankin Jun 08 '21 at 02:55
  • David that fixed my problem, thanks! – berkleybaby Jun 08 '21 at 03:00
  • Glad to help. Good luck with your coding! – David C. Rankin Jun 08 '21 at 03:23

0 Answers0