代码之家  ›  专栏  ›  技术社区  ›  dzl

Ofstream将错误的内容写入文件

c++
  •  2
  • dzl  · 技术社区  · 15 年前

    嘿,伙计们,我真的想不出在标题中该怎么称呼这个错误,下面是。

    我正在开始一项作业,我必须阅读文件的内容,执行一些计算,并将内容+新计算写入一个文件。

    我写了要在文件中读取的代码,并立即将其写入输出文件以测试读取是否正确。当我这样做的时候,我看到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蓝色电动起泡器5 1026
    1039绿色电动起泡器10 1026
    1054蓝色电除霜器(镁涂层)7 2000
    1069杰洛锤V2 111 12
    1050喇叭消声器0 50
    1090蛇油34 150
    1070 Mechagodzilla服装(粉色)1 5000
    1090制冷剂3 9999
    1091制冷剂补充(5包)1 4999
    1092制冷剂补充(每包10个)1 8999
    2003年今天(3月)泡沫化4 5
    2004年泡沫化今天(4月)9 5
    2005年今天(5月)泡沫化25
    3102弗罗布拉托客户保修2年3 199
    3103 Frobulator客户保修3年3 299

    下面是输出文本:

    1034蓝色电动起泡器5 1026
    1039绿色电动起泡器10 1026
    1054蓝色电除霜器(镁涂层)7 2000
    1069杰洛锤V2 111 12
    1050喇叭消声器0 50
    1090蛇油34 150
    1070 Mechagodzilla服装(粉色)1 5000
    1090 rinvoice.txteforbulator 3 9999
    1091制冷剂补充(5包)1 4999
    1092制冷剂补充(每包10个)1 8999
    2003年今天(3月)泡沫化4 5
    2004年泡沫化今天(4月)9 5
    2005年今天(5月)泡沫化25
    3102弗罗布拉托客户保修2年3 199
    3103发票.txtrobutor客户保修3年3 299
    填充(5包)1 4999
    1092制冷剂补充(每包10个)1 8999
    2003年今天(3月)泡沫化4 5
    2004年泡沫化今天(4月)9 5
    2005年今天(5月)泡沫化25
    3102弗罗布拉托客户保修2年3 199
    3103发票.txt

    如您所见,“invoice.txt”不应该出现在输出中。现在我错过了什么?

    2 回复  |  直到 15 年前
        1
  •  3
  •   anon    15 年前

    逐行读取文件的正确方法是:

    string line;
    while( getline( file, line ) ) {
       // do something with line
    }
    

    为什么会这样,你可能想看看 this blog post 我的。

        2
  •  2
  •   dmckee --- ex-moderator kitten    15 年前

    我认为你的问题在这里:

    infile.read(currentLine, 256);
    

    因为我注意到 read

    是一个未格式化的输入函数,提取的内容不会存储为C字符串格式,因此不会在字符序列的末尾附加结束的空字符。

    所以当你复制currentline的时候,拷贝会从末尾直接进入内存中的其他部分,而这恰好是 filename .