Archived

This topic is now archived and is closed to further replies.

C++ read a text file line by line and put each line to an array

This topic is 5115 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, I need help in C++ I am trying to write a program but I am stuck as I have to read a serial text file .txt which is like this: 1 2 3 4 5 6 7 .....till 100 but can also be less 23 34 34 5 4 54 ...till the number of the first line The first line is like the ID and the other one the score (or anything) of each ID. So what I need to know is how to read a text file line by line and put each line to an array which I don''t know it''s length...actually that''s a string. Any help would be really helpfull ! Regards, Dimitris

Share this post


Link to post
Share on other sites
It would be easier to use a member of stl then an array

*note if I get something wrong I'm not around a compiler so I can't check it*

std::fstream("file.txt") _file;
std::list<int, std::string> _filelines;


//Add's member to list

int linecount = 0;
while(!_file.eof()) // Add's all lines to a list

{
++linecount;
_filelines[linecount] = _file.getline();
}

// Prints every line in the list

for(std::list<int, std::string>::iterator printlist = _filelines.begin(); printlist != _filelines.end(); ++printlist)
{
std::cout << (*printlist).second.c_str() << std::endl;
}
// or (assuming you know what line you are looking for.)

for(int i = 0; i <= linecount; i++)
{
std::cout << _filelines[i].c_str() << std::endl;
}


[edited by - PumpkinPieman on December 16, 2003 12:24:04 PM]

Share this post


Link to post
Share on other sites