Jul 8, 2015 at 7:46pm UTC
Hi,
I'm pretty new to C++, and wanted to try and read a simple csv file. The format of the file is:
5
1,4
15,23
54,7
9,7
How do I read and store these values as integers? I was thinking of saving them in a vector, but I am not clear on how to read them in the first place.
And yes, the first row in the file has only a single value.
Jul 8, 2015 at 8:24pm UTC
I was thinking of saving them in a vector
yeah why not
use std::ifstream! (and a bunch of other std facilities)
Not the most elegant way but it should show you how you could do it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include <fstream>
#include <utility>
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
int main()
{
std::ifstream file("test.csv" );
std::vector<std::vector<int > > data;
int dummy;
std::string temp;
while (std::getline(file, temp)) // read each line
{
std::stringstream stream(std::move(temp));
data.push_back(std::vector<int >()); // add row
// split the entries on ','
while (std::getline(stream, temp, ',' ))
{
data.back().push_back(std::stoi(temp)); // add entry in last row
}
}
// print result
for (const auto & row : data) {
for (const auto & e : row)
std::cout << e << ' ' ;
std::cout << '\n' ;
}
return 0;
}
Last edited on Jul 8, 2015 at 8:24pm UTC
Jul 8, 2015 at 10:08pm UTC
Thank you! That helped a lot!