向量的输出向量到带有制表符分隔符的文本文件 C++

Output vector of vector to text file with tab delimiter C++

我正在尝试将 2D 矢量输出到 txt 文件中,问题是我在行末获得额外的制表符,在文本的末尾获得新行 这是我的代码

 int main()
{

    vector< vector<double> > mv;
    vector< vector<double> >::iterator row;
    vector<double>::iterator col;
    ofstream output_file("Mat.txt");
    setVector(mv,5,5);
    for(row = mv.begin(); row != mv.end();row++)
    {
        for(col = row->begin();col != row->end();col++)
        {
            output_file << *col << '\t';
        }
       output_file << '\n';
    }


    return 0;
}

输出样本:

两种解题方式:

  1. 检查是否打印最后一个元素,不要打印 tab/newline。

  2. 检查是否打印第一个元素,如果不是,则打印 leading tab/newline.

随便写

for(row = mv.begin(); row != mv.end();row++)
{
    if(row != mv.begin()) {
         output_file << '\n';
    }
    for(col = row->begin();col != row->end();col++)
    {
        if(col != row->begin) {
            output_file << '\t';
        }
        output_file << *col;
    }
}

重新安排我们的代码,使 row 在内循环中,而 col 在外循环中。如果您的命名约定有意义,那将是解决问题的一大步。

备选方案:

for ( row = mv.begin(); row != mv.end(); ++row )
{
    std::string outs;
    for ( col = row->begin(); col != row->end(); ++col )
    {
        outs += *col;
        outs += '\t';
    }
    outs[outs.length() - 1] = '\n';
    output_file << outs;
}