-2

For the life of me, I can't seem to figure out how to do this properly.

First, I read a line from a csv file. Lets say, that line has 2992854,BOB,3452,394832

I don't want to read each result into a console like practically every example I've found, I want them to go in order, into these 4 variables:

int time;
string name;
int location;
int point;

Right now, this is my code:

    string line;
    ifstream inputFile("input.csv");

    std::list<Cramista> Cramistas;

    while (!inputFile.eof())
     {
        int time;
        string name;
        int location;
        int point;

        std::vector<std::string> stringArray;
        std::size_t position = 0, found;

        getline(inputFile, line);

        while ((found = line.find_first_of(',', position)) != std::string::npos)
        {
            stringArray.push_back(line.substr(position, found - position));
            position = found + 1;
        }

        time = stoi(stringArray[0]);
        name = stringArray[1];
        location = stoi(stringArray[2]);
        point = stoi(stringArray[3]);

    }

UPDATED: So, with what I have here, I'm able to get the first 3 out of 4 pieces of the line, and put them into an array, which I can then move into variables. Trying to figure out how to get that 4th part.

I've got 2992854, BOB, and 3452 but I don't have 394832.

BigBlackBunny
  • 77
  • 1
  • 5
  • 2
    yout googling skills aren't that great, to be honest. `std::stringstream`. 'nuff said. – Marcus Müller Nov 05 '17 at 20:16
  • Please tell me who said that looping until `eof()` was a good idea so I can punch them. –  Nov 05 '17 at 20:19
  • Improve your Googling skills: [StackOverflow C++ read file csv](https://www.google.com/search?q=stackoverflow+c%2B%2B+read+file+csv&ie=utf-8&oe=utf-8). There's gotta be at least one duplicate in there. – Thomas Matthews Nov 05 '17 at 20:20
  • See also: `std::getline(cin, text_string, ',');` – Thomas Matthews Nov 05 '17 at 20:22
  • @MartinBroadhurst I don't think it's anybody's fault. It's one of those intuitive things that just turns out to be wrong. Note to asker: It's wrong because it tests before the read takes place. How will you know if you've reached the end of the file before you look? – user4581301 Nov 05 '17 at 20:52
  • I found eof() used in multiple examples. If you have a better way, I would really like to know what that better way is. – BigBlackBunny Nov 05 '17 at 20:55
  • The 4th part doesn't end with a comma, so `find_first_of` returns `npos` and you leave the while-loop. – Bo Persson Nov 05 '17 at 23:52

1 Answers1

0

I mean basically in order to avoid "reading each result into the console" using

cin >> time >> name >> location >> point;

you would have to split the line by commas (assuming it's a string, then convert the non string data to integers.

j.gooch
  • 305
  • 1
  • 4
  • 21