Read a \t and \n separated file

Hello,

I have a file which separated each line with \n and in each line, each data is separated by \t, that is;
A \t B \t C \n

I try to read this file and assign it into array, but I got stuck in getting next tab. How can I read the next tab?

Thanks in advacne.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>
using namespace std;


int main()
{
	ifstream file("abc.txt");

	char text[10];

	char buffer[256];

	file.getline(buffer, 256, '\n');
	for (int i = 0; buffer[i] != '\t'; i++) {
		buffer[i] = text[i];
	}

	return 0;
}
If the number of data in each line is unknown then it is better to use some standard container as for example std::vector or std::list. As for splitting each line into data elements then you should use std::istringstream and the same getline function.
Last edited on
Thanks for your reply dude.
Is it possible to use 2D array instead of vector?
Suppose I know the maximum data in each row, is it possible to not to use istringstream?
Sorry for that as I am very new to C++. :(
If you indeed know the maximum number of data in each row then you can use a 2D array. But the problem is how to distinguish an actual data in a row from an empty slot that is you need to support an additional array of numbers of actual data in each row of the 2D array.
Thank you. After some reading about istringstream I still cannot figure it out how to use. Until now I only successfully separated the tab by using:

1
2
3
4
5
	stringstream iss(buffer);
	string temp;
	while ( getline(iss, temp, '\t') ) {
		cout << temp << endl;
	}


How to assign each data with specific field?
Suppose I have a txt file:
ID \t Name \t Score \n
I wish to store ID to int ID, Name to string Name and Score to int Score?
Thanks!
You can use this code snip as a base for your code.

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
struct record
{
   int ID;
   std::string Name;
   int Score;
};

std::ifstream file( "abc.txt" );
std::vector<record> v;

std::string line;

while ( std::getline( file, line ) )
{
   std::istringstream is( line );
   record r;
   std::string s;

   std::getline( is, s, '\t' );
   r.ID = std::stoi( s );
   std::getline( is, r.Name, '\t' );
   std::getline( is, s, '\t' );
   r.Score = std::stoi( s );

   v.push_back( r );
}


Topic archived. No new replies allowed.