如何使一个函数,声明为字符串,结束行
how can I make a function ,declared as a string, end the line
我有一个函数,可以从文本文件中读取并输出整个文本文件。它看起来像这样;
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'
是换行符的转义代码。
相关文章:
- 当字符串为"\0"时如何结束 2D 字符数组?
- C++ char 数组特征:为什么字符串在数组结束之前停止?
- 无法打印带有标准::结束的字符串
- 永无止境的 while-循环C++即在输入字符串 == no 时结束
- gvim 换行应该结束当前字符串并在下一行开始一个新的字符串
- 如何使std::getline在字符串流结束时通知我
- 字符串文本的C++宏开始迭代器和结束迭代器
- 结束进程错误代码 -1,如果访问结构的字符串字段
- 正则表达式在开头单独匹配单词,或者在输入结束时通过不重复字符串附加到某些内容但附加到某些内容
- std::字符串在开始和结束之间替换
- 为什么我读的所有字符串在打印它们时都以相等的方式结束
- 替换字符,如替换全部(字符串,开始,结束,"_","-")
- 使用模板<类输入迭代器>字符串(输入迭代器开始,输入迭代器结束)时出现奇怪的错误;
- 在开始和结束处添加的C++字符串
- 结束字符串标记中的while循环
- 如何使一个函数,声明为字符串,结束行
- 从char数组中获取从起始索引到结束的字符串
- 字符串短语以空格结束
- 有一个字符串如何从第一个' /r/n/r/n '得到它的内容,直到2行从字符串结束
- 字符串结束字符会损坏内存吗?缓冲区[大小]='\0';