Search code examples
c++c++buildervcl

Get the second line of a Text File in C++ Builder


My text file looks like this

Fruit 
Vegetable

And I need the function to return Vegetable

This is the code I tried to use and get "Vegetable":

String getItem()
{
ifstream stream("data.txt");

stream.ignore ( 1, '\n' );

std::string line;
std::getline(stream,line);

std::string word;
return word.c_str();
} 

Then I did this to try and put the second line into an edit box:

void __fastcall TMainForm::FormShow(TObject *Sender)
{
    Edit1->Text = getItem();
}

For some reason, when I run the code the Edit Box eventually just has nothing in it, completely blank.


Solution

  • The 1st parameter of istream::ignore() is expressed in characters, not lines. So, when you call stream.ignore(1, '\n'), you are ignoring only 1 character (ie, the F of Fruit), not 1 line.

    To ignore a whole line, you need to pass in std::numeric_limits<streamsize>::max() instead of 1. That tells ignore() to ignore all characters until the specified terminator ('\n') is encountered.

    Also, you are return'ing a blank String. You are ignoring the line that you read with std::getline().

    Try this instead:

    #include <fstream>
    #include <string>
    #include <limits>
    
    String getItem()
    {
        std::ifstream stream("data.txt");
    
        //stream.ignore(1, '\n');
        stream.ignore(std::numeric_limits<streamsize>::max(), '\n');
    
        std::string line;
        std::getline(stream, line);
    
        return line.c_str();
        // or: return String(line.c_str(), line.size());
    }