我有一个程序,它接受用户输入并将其写入文本文件。但是,当我尝试附加到我的文本文件时,它会重写我的“标题”行。我怎么能避免这种情况?
// StudyTime.cpp :
/* Track study time
accept user input
store in .txt file
*/
#include "stdafx.h"
#include <string>
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
string date = "";
double hours = 0;
const string filename = "StudyTime.txt";
ofstream myfile (filename, ios_base::app); //create filename and allow appending
myfile << "Date" << setw(15) << "Study Time" << endl; //Header line
//prompt user for Date
cout << "Date: ";
cin >> date;
//prompt user for hours
cout << "Hours: ";
cin >> hours;
if (date.size() == 3) {
myfile << date << setw(8) << hours << endl; //write date and hours to txt file
}
else if (date.size() == 4) {
myfile << date << setw(7) << hours << endl; //write date and hours to txt file
}
else
myfile << date << setw(6) << hours << endl; //write date and hours to txt file
myfile.close(); //close file
return 0;
}
答案 0 :(得分:1)
你不止一次地运行它。
每次运行时,都会使用ios_base :: app
打开这意味着结果将附加到之前的文件内容中。
每次都要重写文件,请使用ios_base :: trunc
ofstream myfile (filename, ios_base::trunc);
另外,您也可以只写一行而不是if / else if / else:
myfile << date << setw(11 - date.size()) << hours << endl; //write date and hours to txt file
如果你想追加,你需要决定是否写标题,检查文件是否存在:Fastest way to check if a file exist using standard C++/C++11/C?
例如:
ifstream f(filename);
bool exists = f.good();
f.close();
答案 1 :(得分:0)
在添加标题之前,您可以检查文件以查看它是否已有标题。下面的代码应该有效。我添加了一个函数hasHeader
,用于检查文件中是否已存在标头,如果是,则返回true
。在这种情况下,不会附加标题。
#include "stdafx.h"
#include <string>
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
bool fileHasHeader(string file)
{
char line[100];
ifstream myfile;
myfile.open(file, ifstream::in);
myfile.getline(line, 100);
bool hasHeader = false;
if (strcmp(line, "Date Study Time") == 0) {
hasHeader = true;
}
myfile.close();
return hasHeader;
}
int main()
{
string date = "";
double hours = 0;
const string filename = "StudyTime.txt";
ofstream myfile (filename, ios_base::app); //create filename and allow appending
if (!fileHasHeader(filename)) {
myfile << "Date" << setw(15) << "Study Time" << endl; //Header line
}
//prompt user for Date
cout << "Date: ";
cin >> date;
//prompt user for hours
cout << "Hours: ";
cin >> hours;
if (date.size() == 3) {
myfile << date << setw(8) << hours << endl; //write date and hours to txt file
}
else if (date.size() == 4) {
myfile << date << setw(7) << hours << endl; //write date and hours to txt file
}
else
myfile << date << setw(6) << hours << endl; //write date and hours to txt file
myfile.close(); //close file
return 0;
}