Software & Finance





Visual C++ STL - Reading a line from a text file using STL stream





 

We know how to use STL streams. Refer to my earlier articles on copying files using STL stream.

 

How can we read a single line using STL ifstream? We need to check for '\n' by reading each and every character one by one.

 

bool readline(std::ifstream &ifs, std::string &data)

{

    if(ifs.eof())

        return false;

 

    data = "";

    while(1)

    {

        char ch[2];

        ifs.read(ch, 1);

        if(ifs.gcount() < 1)

            break;

        ch[1] = '\0';

        data += std::string(ch);

        if(ch[0] == '\n')

            break;

    }

    return true;

}