Link to home
Start Free TrialLog in
Avatar of Aaeshah
Aaeshah

asked on

C++ : Reading file and store data in multi-vector

I am trying to read data file with this format:

T1: I1,I2,I5
T2: I2,I4
T3: I2,I3
T4: I1,I2,I4
T5: I1,I3
T6: I2,I3
T7: I1,I3
T8: I1,I2,I3,I5
T9: I1,I2,I3

I don't want to read the first column T1,T2,T3 ...... , but each line will be a dataset I want to start read after (space '  ' ) and end with each line and how can I separate the data according to (comma ',')

I wrote this code but it didn't work correctly and it reads the first column anyway

string CItem;

// set of elements
set< CItem > CItemSet;

//Transactions
 CItemSet CTransaction;

// set of transactions
vector< CTransaction > CTransactionSet;

ifstream inFile(inFileName);
	if (!inFile)
	{
		cout << "Failed to open input file filename:." << inFileName;
	}

CTransactionSet transSet;
	CTransaction tran;
	string txtLine;
	// read every line from the stream
	while (getline(inFile, txtLine))
	{
		
		istringstream txtStream(txtLine);
		string txtElement;
		// read every element from the line that is seperated by commas
		// and put it into the vector or strings
		
		while (getline(txtStream, txtElement, ','))
		{
			if (txtElement == ": ") break;
			else tran.insert(txtElement);
		}
		transSet.push_back(tran);
	}

Open in new window

Avatar of Karrtik Iyer
Karrtik Iyer
Flag of India image

I suggest you simply do a get line first to read entire lines as in the file, then perform string operations to get the required data.
1) read  entire line, so you will get 4-5 strings (number of rows)
2) then perform substring to remove T1,T2 part..
3) the perform string split with comma as the separator to get the individual values.
Your below line of code :
while (getline(txtStream, txtElement, ','))
Shall return T1: I1
So your if condition shall never succeed to break (one more thing ideally instead of break you should do continue since you want other data in the row), the string shall never match to be only ":"
Hence you shall always get T1 as well in your vector which you wanted to skip...
Avatar of Aaeshah
Aaeshah

ASKER

Could you please show me an example how to perform substring to remove T1,T2 part..
and how to split them in a code, Please!
ASKER CERTIFIED SOLUTION
Avatar of Karrtik Iyer
Karrtik Iyer
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Aaeshah

ASKER

Thank you very much that solve my problem using .ignore is all I need. Thanks again