0

我试图写回以前在程序中读取的 csv 文件。该程序目前看起来像这样:

ifstream file;

    file.open ("file");

    e=0;

    while (file.good()) {

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var1[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var2[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var3[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var4[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var5[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var6[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var7[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var8[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var9[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var10[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var11[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var12[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var13[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var14[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var15[e]=infoc;

        ++e;

    }



    var1[e] = var1[e] + v1;
    var2[e] = var2[e] + v2;
    var3[e] = var3[e] + v3;
    var4[e] = var4[e] + v4;
    var5[e] = var5[e] + v5;
    var6[e] = var6[e] + v6;
    var7[e] = var7[e] + v7;
    var8[e] = var8[e] + v8;
    var9[e] = var9[e] + v9;
    var10[e] = var10[e] + v10;
    var11[e] = var11[e] + v11;
    var12[e] = var12[e] + v12;
    var13[e] = var13[e] + v13;
    var14[e] = var14[e] + v14;
    var15[e] = var15[e] + v15;
    //WRITE TO compYTD

    file.close();

在我关闭文件之前,我想将新的计算变量写回文件,擦除之前读取的所有内容。有没有允许我这样做的功能?还有一个单独的函数允许我写回这个文件,添加到已经存在的行吗?

4

1 回答 1

0

我个人会关闭文件,然后使用以下内容写入新值:

ofstream ofile("file.csv"); 

for(int i = 0; i < e; i++)
   ofile << var1[i] << ", " << var2[i] << ", " << var3[i] << ", " << ... endl;

ofile.close();

(当然,如果var1, var2etc 在数组或向量中会容易得多 - 当然读取它也是一样的 - 只是 , 等的一个实例getlineistringstream

要附加(将信息添加到文件末尾)文件,您可以将ios_base::app其用作ofstream. 再次,您关闭输入文件,并在以下位置打开输出ofstream

    ofstream ofile("file.csv", ios_base::app); 

您写入文件的任何内容现在都将位于文件的末尾。

于 2013-08-06T18:40:48.040 回答