c++ - 我怎样才能创建一个声明为字符串的函数,结束该行

标签 c++ string function endl

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

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

如果我使用 返回输出 + "\n"

我得到这个作为输出

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

关于c++ - 我怎样才能创建一个声明为字符串的函数,结束该行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18085789/

相关文章:

c++ - 从相同类型的静态成员进行类内初始化

c++ - Eigen 对 Rows 模板的可变模板扩展有问题

c - "%"符号后面的数字有什么作用?

.net - 如何将 System::String^ 转换为 std::string?

php - 如何在不转到 php.ini 文件的情况下禁用 eval 函数?

c++ - 如何初始化 std::set 比较器?

c++ - 使用LD链接中间文件

java - 根据我的要求在java中按长度分割字符串

javascript - 如何使用 onclick 函数删除数组中的项目?

javascript - 传递函数不求值