嘿伙计们,我真的不能想到在标题中称这个错误为什么,所以这里有。
我正在开始一项任务,我必须阅读文件内容,执行一些计算并将内容+新计算写入文件。
我编写了要在文件中读取的代码,并立即将其写入输出文件以测试读取是否正确。当我这样做时,我看到ofstream将我的“文件名”字符串(用于询问用户要打开的文件的名称)写入随机位置的文件中,并且在代码中没有提及它。
这是我的代码:
#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这是输出文本:
1034 BLUE ELECTRIC FROBULATOR 5 1026
1039 GREEN ELECTRIC FROBULATOR 10 1026
1054 BLUE ELECTRIC DEFROBULATOR(镁涂层)7 2000
1069 JELLO HAMMER V2 111 12
1050 BELL SILENCER 0 50
1090 SNAKE OIL 34 150
1070 MECHAGODZILLA COSTUME(PINK)1 5000
1090 Rinvoice.txtEFROBULATOR 3 9999
1091 REFROBULATOR REFILL(5包)1 4999
1092 REFROBULATOR REFILL(PACK OF 10)1 8999
2003年今日结束(MAR)4 5 2004年今日流产(APR)9 5 2005年度今日(5月)2 5周年 3102 FROBULATOR客户保修2YR 3 199
3103 invoice.txtFROBULATOR客户保修3YR 3 299
填充(包装5)1 4999
1092 REFROBULATOR REFILL(PACK OF 10)1 8999
2003年今日结束(MAR)4 5 2004年今日流产(APR)9 5 2005年度今日(5月)2 5周年 3102 FROBULATOR客户保修2YR 3 199
3103 invoice.txt
如您所见,“invoice.txt”不应出现在输出中。现在我错过了什么?
答案 0 :(得分:3)
逐行读取文件的正确方法是:
string line;
while( getline( file, line ) ) {
// do something with line
}
为什么会这样,你可能想看看我的this blog post。
答案 1 :(得分:2)
我认为你的问题在这里:
infile.read(currentLine, 256);
因为我注意到read
是未格式化的输入函数,提取的内容不会以c字符串格式存储,因此在字符序列的末尾不会附加结尾的空字符。
因此,当你去复制currentLine时,副本会直接走到那里的内存中的任何其他内容,恰好是filename
。