如何使一个函数,声明为字符串,结束行

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

本文关键字:字符串 结束 声明 函数 何使一      更新时间:2023-10-16

我有一个函数,可以从文本文件中读取并输出整个文本文件。它看起来像这样;

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;
};

我像这样调用函数;

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

如果我使用 返回输出 + "">

我得到这个作为输出

-- 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.

我不希望字里行间有那个空间。

因此,在调用函数后,我需要结束该行。如何在函数中执行此操作?

附言。此外,如果有比我这样做的方式更好的方法在文本文件中输出所有内容,我将不胜感激任何建议。

只需更改

return output;

return output + "n";

这个:

因此,在调用函数后,我需要结束该行。怎么能 我在函数中这样做?

是无厘头的。您无法在调用函数后在函数中执行任何应该发生的操作。如果调用代码在应该发送时没有将std::endl发送到cout,这是调用代码的问题,你不能 - 也不应该 - 尝试在你的函数中解决这个问题。

简体:

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;

只需返回 output + 'n' 而不仅仅是 output'n' 是换行符的转义代码。