split by line then ,

if i have a string like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
testuser82, 22675, Test, 2, 1, , , , , , ,
carlsum, 22674, Carl Sum, 4115, 1, 65--84279319, 65--67353779, , , , 11311, 1
newuser82, 22677, test, 2, 1, , , , , , ,
newuser2, 22679, test, 3573, 1, , , , , , ,
test9@ngvt, 22681, test, 2, 1, 13551077329, , , , , 11311, 1
henky@xlcs, 22682, Henky, 2, 1, 6567353779, , , , , 11311, 1
henky@xchange, 9801, Henky, 2, 1, , , , , , ,
yuan.jiun@ociss, 11264, Yuan Jiun Lai, 1, 1, , , , , , ,
qianshuren@ngv, 20236, Qian ShuRen, 4115, 1, 86-21-62360999, 86--15000208895, 15689002, , , 11311, 1
lvfengjun@ngv, 20237, Gavin Lv FengJun, 4115, 1, , 86--13551077329, 15689001, , , 11311, 2
gavinlvfj@ngv, 20572, gavinlvfj, 4115, 1, 86--1362432432421, , , , , 11311, 1
test8@ngv, 22680, test, 3573, 1, , , , , , ,
tester, 20573, Test Account, 4115, 1, 86-21-12121, , , , , 11311, 1
r&d-20100530, 21168, R&D-20100530, 4115, 1, , , , , , ,
xxx-0000001, 22178, xxx-0000001, 1, 1, , , , , , ,
xxx-0000002, 22179, xxx-0000002, 1, 1, , , , , , ,
test82, 22676, test, 2, 1, , , , , , ,
test44, 22673, test, 2, 1, 6584279319, , , , , 11311, 1



how do i split by line then ","
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
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;

int main ()
{
    string line;
    char col[256];
    ifstream myfile ("example.txt");
    if (myfile.is_open())
    {
        while (! myfile.eof() )
        {
            getline (myfile,line); //split by line
            stringstream ss(line);
            while( !ss.eof() )
            {
                ss.getline(col, 256, ','); //split by ','
                cout << col << endl;
            }
            cout << "============================================================\n";
        }
        myfile.close();
    }

    else cout << "Unable to open file";

    return 0;
}


[read more]
http://cplusplus.com/doc/tutorial/files/
http://cplusplus.com/reference/string/getline/
http://cplusplus.com/reference/iostream/istream/getline/
http://cplusplus.com/reference/iostream/stringstream/
You should never do a while on eof() because eof() is not set until after the attempt to read. So doing it that way will mean you process at least one bad line. You should put the std::getline() in the while() clause:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <fstream>
#include <sstream>

int main()
{
	std::ifstream ifs("input.csv");

	// extract each whole row as a line from
	// the input file stream
	std::string row;
	while(std::getline(ifs, row))
	{
		// put whole row into an input stream
		std::istringstream iss(row);

		// extract each column from the row
		std::string col;
		while(std::getline(iss, col, ','))
		{
			// ... do stuff ...
		}
	}
}
Topic archived. No new replies allowed.