0

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...

2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by sfuo
0

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;
}
0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.