简体   繁体   中英

Using getline and istringstream to read data from CSV file

I'm trying to read a CSV file with entries like this:

//2009-12-31 21:00:00, COUNTRY ,1.84296,350.947,60.72

This is what I did

#include <iostream>
#include <fstream>
#include <sstream>

int main()
{
    using namespace std;
    ifstream read("data.csv");

    string line;

    //I want to use this to hold the data temporarily
    string temp[5];

    while (std::getline(read, line))
    {
        int i=0;
        std::istringstream iss(line); // string stream
        while(std::getline(iss, temp[i], ','))
        {
            cout << i << ": " << temp[i] << endl;
            ++i;
        };
    }
}

But it didn't do what I wanted the code to do. In particular, the code stopped after the integer i hit 21. Here's the output

 0: 2009-12-31 21:00:00 1: GRID_A 2: 1.84296 3: 350.947 4: 60.72 2010-01-01 00:00:00 5: GRID_A 6: 1.93569 7: 348.98 8: 60.64 2010-01-01 03:00:00 9: GRID_A 10: 2.30688 11: 339.444 12: 247.6 2010-01-01 06:00:00 13: GRID_A 14: 1.74453 15: 326.219 16: 587.92 2010-01-01 09:00:00 17: GRID_A 18: 2.16002 19: 289.19 20: 180.72 2010-01-01 12:00:00 21: GRID_A 

Then I got an error like this

 _LIBCPP_INLINE_VISIBILITY static void assign(char_type& __c1, const char_type& __c2) _NOEXCEPT {__c1 = __c2;} Thread 1: EXC_BAD_ACCESS... 

Can you please tell me what's wrong? Many thanks!

PS: It turns out that the problem had to do with the CSV file that I saved using Excel on my Mac. The newline character was missing.

Your code works if there are only 5 columns in each line. If i is greaten than 4 you will get problems. As you said your i is 21! Your array can't take this much elements. You should leave the loop at the end if i is outside your array range.

You try to access temp[21] which is somewhere beyond the rainbow. No wonder you get BAD ACCESS.

Just use temp as a single string. No need for an array if you only want to output the value. Just use string temp; and remove [i] down there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM