-1

I would like to use C++ to read a .CSV file and extract each line and put each element separated by ',' into a 2D array. but there seems to be error in the reading and i cannot find the problem.

My C++ Code:

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

using namespace std;  

int main( )  
{     
    std::string line2;  

    ifstream in2("sample-to-remove.txt");

    string entryLine[10][2];
    int x = 0;

    while (!in2.eof())
    {
        getline(in2, line2, '\n');
        stringstream ss(line2);

        std::string token;
        int y=0;
        while (std::getline(ss, token, ','))
        {
            std::cout << token << '\t';
            entryLine[x][y] = token;
            y++;
        }
        x++;
    }

    for(int a= 0 ;  a < 10 ; a++ )
    {
        for(int b= 0 ;  b < 2 ; b++ )
        {
            cout << entryLine[a][b] << endl;
        }
    }

    in2.close();      

    return 0; 
}

My CSV File:

9834117,audriwxh@gmail.com
9234049,calinwj@hotmail.com
sgchecker
  • 63
  • 7
  • Related, have you [seen this question](https://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c)? – WhozCraig Apr 11 '15 at 02:21
  • `getline` then send to `stringstream` then pass via `getline(..., ',')`. Just take a look/research about it, and you'll figure out. Your code seems correct, so better post out an error, or why do you think it's not working. – vsoftco Apr 11 '15 at 02:24

1 Answers1

1

Errors that I see:

  1. The logic for getting out of the outer while loop is not right.

    After the you finish reading the first two lines, in2.eof() is still fasle. Hence, you continue to read a non-existent third line.

    Instead of

    while (!in2.eof())
    

    use

    while (getline(in2, line2, '\n'))
    
  2. The printing loop prints too many lines.

    Instead of

    for(int a= 0 ;  a < 10 ; a++ )
    

    use

    for(int a= 0 ;  a < x ; a++ )
                   //  ^^^ You only have x lines not 10 lines.
    
R Sahu
  • 204,454
  • 14
  • 159
  • 270