在循环cpp中写入文件

时间:2016-01-20 16:48:48

标签: c++ ostream

在循环中和循环外写入文件的一般问题:

假设我有以下代码:

# include <iostream>
# include <string>
# include <fstream>
# include <sstream>

using namespace std;
void printToFile(string name, double **Array) 
{
    ofstream myfile;
    myfile.open(name);
    for (unsigned int m=0; m<5; m++)
    {
        for (unsigned int n=0; n<10; n++)
        {
            myfile << Array[m][n] << " ";
        }
    }
    myfile.close();
}

int main()
{
    int i,j;
    double **Arr;
    string str;
    ostringstream oss;

    for (i=0; i<5; i++)
    {           
        for (j=0; j<10; j++)
        {
            // some calculation that yields Arr with size [5][10]
            str="";
            oss << "Arr_j_"<<j+1<<"_i_"<<i+1<<".txt";
            str = oss.str();
            printToFile(str,Arr);
        } 
    } 
    return 0;
}

我似乎无法正确获取文件的名称,我得到的是:

Arr_j_1_i_1.txtArr_j_2_i_1.txtArr... etc

此外,我的代码运行完成,但输出文件停在i=2,我也很感激有关使用哪种流量的评论(ostreamfstreamsstream,等...)

2 个答案:

答案 0 :(得分:3)

每次迭代后,您永远不会清除ostringstream。要自动执行此操作,您只需将oss声明移动到循环中即可。这样,在每个循环之后,流将被销毁,并且您将在下一次迭代时以新流开始。

for (i=0; i<5; i++)
{           
    for (j=0; j<10; j++)
    {
        ostringstream oss;
        // some calculation that yields Arr with size [5][10]
        oss << "Arr_j_"<<j+1<<"_i_"<<i+1<<".txt";
        printToFile(oss.str(),Arr);
    } 
} 

我还删除了str=""str = oss.str();,因为它不需要。您可以使用oss.str()作为printToFile的参数,并删除str

我不确定它是否会更快但你可以避免使用任何类型的stringstream并使用std::to_string在函数调用中构造字符串以将索引转换为字符串。看起来像

for (i=0; i<5; i++)
{           
    for (j=0; j<10; j++)
    {
        // some calculation that yields Arr with size [5][10]
        printToFile("Arr_j_" + std::to_string(j+1) + "_i_" + std::to_string(i+1) + ".txt", Arr);
    } 
} 

答案 1 :(得分:0)

在循环中声明str和oss,你没有清除oss

  for (i=0; i<5; i++)
    {           
        for (j=0; j<10; j++)
        {
            // some calculation that yields Arr with size [5][10]
            string str;
            ostringstream oss;
            oss << "Arr_j_"<<j+1<<"_i_"<<i+1<<".txt";
            str = oss.str();
            printToFile(str,Arr);
        } 
    } 
相关问题