![](/img/trans.png)
[英]How can I make function that take a string and return a char array
[英]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
如果我使用return輸出+“ \\ 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.
我不希望線之間有空隙。
因此,在調用函數之后,我需要結束這一行。 我如何在函數中執行此操作?
PS。 另外,如果有比我完成的方法更好的方法來將所有內容輸出到文本文件中,我將不勝感激。
只需更改
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'
是換行符的轉義代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.