I have a text file for example


abc, cde,fgh, jkl, rty
qwe,erty, tyujk,werty , lkjh

I want to read these tokens from the text file, into different variables row wise (ie one row at at time)
Number of tokens in a row is fixed. (ie 5 in this case)

Please help me out doing this...

Recommended Answers

All 3 Replies

Since you know the data is separated by a ',' then you have to read in the data in chunks between the ','.

Below is some code I quickly threw together that takes in the data from the text file and stores it into data[].


data.txt

abc,cde,fgh,jkl,rty
qwe,erty, tyujk,werty,lkjh

main.cpp

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

int main()
{
	ifstream in("data.txt");
	int sz = 5;
	string data[sz];

	while( getline(in, data[0], ',') )
	{
		for( int i = 1; i < sz; i++ )
		{
			if( i == sz-1 )
				getline(in, data[i]); //since the end of the row ends with a \n
			else
				getline(in, data[i], ',');
		}
		
		//do stuff with the data here

		for( int i = 0; i < sz; i++ )
			cout << data[i] << " ";
		cout << endl;
	}

	return 0;
}

but how is this code traversing the whole text file???????

On line 11 of what I posted the while() loop will run until the end of the file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.