reading .csv file into 2d array

#include <iostream>
#include <fstream>
using namespace std;

double data[38][27];
int count = 1;
int bigcount = 1;

int main() {

ifstream file;
file.open("sheet.csv");

while (bigcount < 39)
{
while (count < 28)
{

getline(file, data[bigcount][count], ',');
count++;
}

bigcount++;

}

file.close();
return 0;
}


This code is supposed to put read a .csv file into a 2d array. Im pretty sure you cant do this but i dont know how im supposed to change it in a way that it still works.
The prototype for std::getline is something like this:
std::getline( istream& , string , char = '\n');

You can only pass a string into this, not a double. You can use a stringstream with the >> operator to read in a double.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
ifstream file("sheet.csv");

for(int row = 0; row < 38; ++row)
{
    std::string line;
    std::getline(file, line);
    if ( !file.good() ) 
        break;

    std::stringstream iss(line);

    for (int col = 0; col < 27; ++col)
    {
        std::string val;
        std::getline(iss, val, ',');
        if ( !iss.good() ) 
            break;

        std::stringstream convertor(val);
        convertor >> data[row][col];
    }
}
thanks so much for this, but now it sais:

main.cpp:24:31: error: variable ‘std::stringstream iss’ has initializer but incomplete type
main.cpp:33:40: error: variable ‘std::stringstream convertor’ has initializer but incomplete type

apparently there is an incomplete type for these two commands:

std::stringstream iss(line);
std::getline(iss, val, ',');

But either way, thanks for the help so far.

if you can help pleas post a answer
Last edited on
Hmmm I'm not getting this error. I've just compiled in g++ in Linux. This is the full thing. What compiler are you using?
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
#include <fstream>
#include <sstream>

int main()
{
    float data[38][27];
    std::ifstream file("sheet.csv");

    for(int row = 0; row < 38; ++row)
    {
        std::string line;
        std::getline(file, line);
        if ( !file.good() )
            break;

        std::stringstream iss(line);

        for (int col = 0; col < 27; ++col)
        {
            std::string val;
            std::getline(iss, val, ',');
            if ( !iss.good() )
                break;

            std::stringstream convertor(val);
            convertor >> data[row][col];
        }
    }
    return 0;
}


Edit:
OOOooohhhh, I bet you didn't include <sstream>. If I #include <string> instead of <sstream> I get that error.

Last edited on
Topic archived. No new replies allowed.