how can I make a function ,declared as a string, end the line

153 Views Asked by At

I have a function that reads from a text file and the outputs the whole text file. It looks like this;

string FileInteraction :: read() const
{
    ifstream file;
    string output;
    string fileName;
    string line;
    string empty = "";


    fileName = getFilename();

    file.open(fileName.c_str());

    if(file.good())
    {
        while(!file.eof())
        {
            getline(file, line);
            output = output + line ;
        }

        file.close();
    return output;
    }
    else
        return empty;

};

I call the function like this;

cout << FI.read(); //PS I cant change the way it's called so I can't simply put an endl here

if I use return output + "\n"

i get this as output

-- Write + Read --
This is the first line. It should disappear by the end of the program.

-- Write + Read --
This is another line. It should remain after the append call.
This call has two lines.

I don't want that space to between the lines to be there.

So after the function has been called I need to end the line. How can I do that within the function?

PS. Also if there is a better way to output everything in a text file than the way I have done it i would appreciate any suggestions.

4

There are 4 best solutions below

0
On

Simply change

return output;

to

return output + "\n";
0
On

Simplified:

std::string fileName = getFilename();
std::ifstream file(fileName.c_str());
std::string output;
std::string line;
while (getline(file, line))
    output.append(line);
output.append(1, '\n');
return output;
0
On

simply return output + '\n' instead of just output. '\n' is the escape code for the new line character.

0
On

This:

So after the function has been called I need to end the line. How can I do that within the function?

is nonsensical. You can't do anything within the function that is supposed to happen after the function has been called. If the calling code doesn't send std::endl to cout when it's supposed to, that's a problem with the calling code, you can't - and shouldn't - try to fix this problem in your function.