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

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

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

问题

  1. fstream file("afile.txt", ios::out | ios::in | ios::app);
  2. if (!file.is_open())
  3. {
  4. cout << "Error Loading File!";
  5. }
  6. else
  7. {
  8. // cout << " File Created ";
  9. }
  10. for (i = 0; i < gameplayed; i++)
  11. {
  12. file << name << " Won $" << prize << " And Answered " << questions << " Questions" << "\n";
  13. }
  14. file.seekg(0);
  15. string line;
  16. while (file.good())
  17. {
  18. getline(file, line);
  19. cout << line;
  20. }

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

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

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

英文:
  1. fstream file(&quot;afile.txt&quot; , ios :: out | ios:: in | ios :: app);
  2. if(!file.is_open())
  3. {
  4. cout &lt;&lt; &quot;Error Loading File!&quot;;
  5. }
  6. else
  7. {
  8. // cout &lt;&lt; &quot; File Created &quot;;
  9. }
  10. for(i = 0 ; i &lt; gameplayed ; i ++)
  11. {
  12. 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;;
  13. }
  14. file.seekg(0);
  15. string line;
  16. while(file.good())
  17. {
  18. getline(file,line);
  19. cout &lt;&lt; line ;
  20. }

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:

确定