【问题标题】:When I write to my file it clears all the previous data in that file当我写入我的文件时,它会清除该文件中的所有先前数据
【发布时间】:2015-03-04 02:27:01
【问题描述】:

我一直在通过 stackoverflow 进行扫描,但没有找到任何关于我的情况的先前帖子。

我想编写的程序只是用来记录每日提示、工作时间和工作天数。到目前为止,它打印并创建了一个tips.txt 文件,但由于某种原因,每次我运行程序输入额外的数字时,它都会清除以前的条目。还有很多工作需要做,但我想先解决这个问题。有任何想法吗?

#include <fstream>
#include <iostream>
using namespace std;
int daysWorked(int); // Caculates the number of days worked
int hoursWorked(int); // Caculates hours worked
double profit(double); // Caculates the profit year to date

int main()
{
double tip;
int hours;
int month, day;
ofstream readFile;

cout << " Enter the month and then the day,  followed by hours worked, followed by money made" << endl;

if (!"tips.txt") // checks to see if tips.txt exists
{
    ofstream readFile("tips.txt"); // if tips.txt doesn't exists creates a .txt
}
else
    readFile.open("tips.txt" , std::ios::app && std::ios::in && std::ios::out); // if tips.txt exits just opens it? 

if (cin >> month >> day >> hours >> tip) // reads in the user input
{
    cout << endl;
    readFile << " Date :" <<  month << "/" <<  day << " " <<  "Hours:" << hours << " " << "Money made: " << tip << endl; // prints out the user input 
    cout << endl;
    readFile.close();
}

return 0;

}

【问题讨论】:

  • if (!"tips.txt") // checks to see if tips.txt exists 这并不像你想象的那样。
  • 您应该使用按位或运算符 | 来组合非逻辑模式和 &amp;&amp; 并且您不将其用于输入,因此 std::ios::in 是不必要的,而 std::ios::out 是隐含的,因为它是一个ofstream,所以readFile 也是一个误导性名称。
  • 这个link 将向您展示如何附加到文件。

标签: c++ fstream ofstream


【解决方案1】:

删除以下代码:

// As rpattiso stated, this does not test for the existence of a file
//if (!"tips.txt") // checks to see if tips.txt exists
//{
//    ofstream readFile("tips.txt"); // if tips.txt doesn't exists creates a .txt
//}
//else

仅此一项就足够了:

// This will create the file if it doesn't exist and open existing files for appending (so you don't need to test if the file exists)
ofstream readFile.open("tips.txt" , std::ios::app); // open for writing in append mode

【讨论】:

  • 啊,非常感谢。这消除了我对打开文件的很多困惑。它奏效了
猜你喜欢
  • 1970-01-01
  • 2022-12-18
  • 2017-03-28
  • 2013-04-05
  • 1970-01-01
  • 2012-09-02
  • 1970-01-01
  • 2019-04-03
  • 2019-08-20
相关资源
最近更新 更多