在每次保存后以这种方式追加文件,使其在每次保存后结束一行,C++。

huangapple go评论74阅读模式
英文:

File Append In Such A Way That It Ends Line After Each Save C++

问题

fstream file("afile.txt", ios::out | ios::in | ios::app);
if (!file.is_open())
{
    cout << "Error Loading File!";
}
else
{
    // cout << " File Created ";
}

for (i = 0; i < gameplayed; i++)
{

    file << name << " Won $" << prize << " And Answered " << questions << " Questions" << "\n";
}

file.seekg(0);
string line;
while (file.good())
{

    getline(file, line);
    cout << line;
}

所以基本上这段代码运行得很好,不会覆盖,但它会像这样立即开始:

"Player Won $2000 Dollars And Answered 6 Questions Player2 Won $2000 Dollars And Answered 6 Questions"

我想要的是它出现像这样,有一个换行符,而不是在其后面。

英文:
fstream file(&quot;afile.txt&quot; , ios :: out | ios:: in | ios :: app);
if(!file.is_open())
{
	cout &lt;&lt; &quot;Error Loading File!&quot;;
}
else
{
	// cout &lt;&lt; &quot; File Created &quot;;
}

for(i = 0 ; i &lt; gameplayed ; i ++)
{

file &lt;&lt;name &lt;&lt; &quot; Won $&quot;  &lt;&lt; prize &lt;&lt; &quot; And Answered &quot; &lt;&lt; questions &lt;&lt; &quot; Questions&quot; &lt;&lt; &quot;\n&quot;;

}
file.seekg(0);
string line;
while(file.good())
{
	
	getline(file,line);
	cout &lt;&lt;  line  ;
}

So basically the codes works perfectly and doesn't overwrite, but it just starts right after like

"Player Won $2000 Dollars And Answered 6 Questions Plater2 Won $2000 Dollars And Answered 6 Questions"

I want is To Appear Like
With a line break and not after it

答案1

得分: 2

This will help you

> 将 std::endl 替换为 "\r\n",以获取回车换行(CRLF),而不仅是换行(LF)。

英文:

This will help you

> Replace std::endl with "\r\n" to get CRLF instead of just LF.

答案2

得分: 1

你的输出确实有换行符。

然而,它没有回车符。

如果你在Windows上阅读文件,在一个区分的应用程序中,你将看不到这个换行。

你可能希望考虑写成\r\n,这是Windows上的标准换行符序列。

英文:

Your output does have line breaks.

However, it doesn't have carriage returns.

If you're reading the file on Windows, in an app that makes a distinction, you won't "see" the break.

You may wish to consider writing \r\n instead, which is the standard line ending sequence on Windows.

huangapple
  • 本文由 发表于 2020年1月6日 20:59:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612575.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定