nimbus
nimbus

Reputation: 141

cplusplus importing csv does not recognise first column?

I'm trying to import a csv file into my c++ program but I am having a few problems and would like some clarification.

The data in the csv file is arranged like below. As you can see there are 12 cells that I would like to import.

x, y, z, p
1, 2, 3, 4
5, 6, 7, 8

My function to import said csv file is the following:

  while ( getline (myfile, stringg, ','))
    {          
        std::cout << "j: " << j << "  " << stringg << std::endl;

        j++; //Note: j counts each cell.
    }
    myfile.close();
}

Everything imports perfectly fine. However it seems j has stopped counting. This shouldn't be the case since the number in the csv file is still being printed.

j: 0 x
j: 1 y
j: 2 z 
j: 3 p
1
j: 4 2
j: 5 3
j: 6 4
5
j: 7 6
j: 8 7
j: 9 8

Now I know why I believe it's doing that. The end of each line does not have a comma at the end. However! This still does not account for why j stopped counting?

Upvotes: 1

Views: 115

Answers (2)

Excelcius
Excelcius

Reputation: 1690

getline is reading the input until the next ',' character. In your case, this means that stringg will contain this:

1. iteration: stringg == "x"
2. iteration: stringg == " y"
3. iteration: stringg == " z"
4. iteration: stringg == " p\n1" // The fourth string contains the next line!

Errors like these should be easily visible when debugging the program.

One approach to solve this problem could be to read line by line using the default getline and inside this loop split the resulting string into further parts using ',' as the separator.

Upvotes: 0

HadeS
HadeS

Reputation: 2038

count of j is correct... if you take a closer look your file will be like this

x, y, z, p'\n'
1, 2, 3, 4'\n'
5, 6, 7, 8'\n'

So when you when the value of j is 3 line read by getline() is p'\n'1 which when printed on console as

j: 3 p
1

after that j is incremented and next token read in 2...same for rest..

Upvotes: 3

Related Questions