0

I have this function that reads the text from a file and adds it to a string, now the weird thing is that it works fine if its a short text. But if its a longer text the string becomes empty, any help solving this problem is appreciated.

 string inlasning(string namn)
{
    string filString, temp;

    ifstream filen(namn.c_str());

    if(!filen.good())
    {
        cout << "Otillganglig fil" << endl;
        filString = "ERROR";
        return filString;
    }
    else
    {
        while(!filen.eof())
            getline(filen, temp);
            filString.append(temp);
    }

    filen.close();
    return filString;

}
cpp
  • 3,503
  • 3
  • 18
  • 35
bryo
  • 39
  • 1
  • 5

3 Answers3

6

1) Don't use eof() to control the loop. Put getline directly into the loop condition. Search StackOverflow if you have problems doing this.

2) Your while loop has no braces and thus only covers the getline line, despite your misleading indentation.

3) getline discards newlines. Your final string will be wrong.

4) The actual behavior you're observing comes from the fact that you only append the very last thing that getline returns to your string. When your file contains one line of text and doesn't end in a newline, this will seem to work. If it has more lines but doesn't end in a newline, you'll only get the last line. If the file does end in a newline, because of your incorrect loop condition the last call to getline will actually give you an empty string, which will be exactly the contents of your string.

Sebastian Redl
  • 61,331
  • 8
  • 105
  • 140
0

Replace

while(!filen.eof())
    getline(filen, temp);
    filString.append(temp);

with

while(!filen.eof())
{
    getline(filen, temp);
    filString.append(temp);
}
cpp
  • 3,503
  • 3
  • 18
  • 35
0

Use "is_open()" to check if the file exists:

if( ! filen.is_open() ){...} // you don't need an else clause

...And your while loop must has braces or it will only execute the getline(...) instruction:

while( filen.good() ) {
    getline( filen , temp );
    filString += ( temp + '\n' );
}

If your file doesn't ends with '\n', remove the last char from the string

mazoti
  • 1