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.
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.
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!
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 );
}