嘿,我真的不知道在标题中怎么称呼这个错误,所以在这里。Ofstream把错误的东西写入文件
我开始了一个任务,我必须读取文件的内容,执行一些计算并将内容+新计算写入文件。
我编写了读取文件的代码,并立即将其写入输出文件以测试读取是否正确发生。正如我所做的那样,我看到ofstream在随机位置将文件的“filename”字符串(用于要求用户输入要打开的文件的名称)写入文件中,并且在代码中没有提及它。
这是我的代码:
#include <string>
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
char filename[256] = "";
char currentLine[256] = "";
cout << "Please enter the name of the input file: " << endl;
cin.getline(filename,256);
vector <string> storage;//disregard for now
ifstream infile;
infile.open(filename);
string outputFile = ".output";
outputFile = filename + outputFile;
ofstream outfile(outputFile.c_str());
string line = "";
while(!infile.eof())
{
infile.read(currentLine, 256);
line = currentLine;
storage.push_back(line); //disregard for now
outfile << line; //testing to see if it read properly
}
}
这里是输入文本:
1034 BLUE ELECTRIC FROBULATOR 5 1026
1039绿色电FROBULATOR 10 1026
1054 BLUE ELECTRIC DEFROBULATOR(镁COATING) 7 2000
1069 JELLO HAMMER V2 111 12
1050 BELL SILENCER 0 50
1090 S纳克OIL 34 150
1070机械哥吉拉COSTUME(PINK)1 5000
1090 REFROBULATOR 3 9999
1091 REFROBULATOR REFILL(5 PACK)1 4999
1092 REFROBULATOR REFILL(OF 10 PACK)1个8999
2003 FROBULATION TODAY( MAR)4 5
2004 FROBULATION TODAY(APR)9 5
2005 FROBULATION今日(五月)2 5
3102 FROBULATOR客户保修2YR 3 199
3103 FROBULATOR客户保修3YR 3 299
,这里是输出文本:
1034 BLUE ELECTRIC FROBULATOR 5 1026
1039绿色电FROBULATOR 10 1026
1054 BLUE ELECTRIC DEFROBULATOR(镁COATING)7 2000
1069 JELLO锤V2 111 12
1050 BELL消音0 50
1090蛇油34 150
1070机械哥吉拉COSTUME(PINK)1 5000
1090 Rinvoice.txtEFROBULATOR 3 9999
1091 REFROBULATOR REFILL(5 PACK)1个4999
1092 REFROBULATOR REFILL(OF 10 PACK)1个8999
2003 FROBULATION TODAY(MAR)4 5
2004 FROBULATION TODAY(APR)9 5
2005 FROBULATION今日(五月)2 5
3102制造商客户担保2年 3103发票。txtFROBULATOR客户保修3YR 3 299
FILL(5 PACK)1 4999
1092 REFROBULATOR REFILL(OF 10 PACK)1个8999
2003 FROBULATION TODAY(MAR)4 5
2004 FROBULATION TODAY(APR)9 5
2005年FROBULATION今日(五月)2 5
3102 FROBULATOR客户保修2YR 3 199
3103 invoice.txt
正如你可以看到 “invoice.txt” 不应该在输出中。现在我错过了什么?
你确定当你开始.output文件是空的吗? – MadcapLaugher 2010-01-17 21:18:22
顺便说一句 - 你将被赞扬写作更清晰的家庭作业相关的问题,我曾经见过一段时间。 – dmckee 2010-01-17 21:20:54
无所谓 - 它会被覆盖。但他应该检查它是否正确打开。 – 2010-01-17 21:21:20