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.