Search code examples
c++flat

Making a flat file from vector array


My plan is to make a flat file in two columns and for that this is what I have initiated two vector arrays. Two vector arrays will be in two column of the flat file. I think the problem I'm having is to fill the vector elements in the columns of flat file. Am I filling in wrong way?

outFile << vec1[i] << "\t" << vec2[i] << endl;

  #include <fstream>
#include <vector>

using namespace std;
//int main()
void ffile()
{
    std::ofstream ofs;
    ofstream outFile;
    outFile.open("flatFile.dat");
     vector<int> vec1{ 10, 20 };
     vector<int> vec2{ 0, 20, 30 };


    for (int i=0; i<=3;i++)

{
  outFile << vec1[i] << "\t" << vec2[i] << endl;
    }
}

Updated question: I have two vector with different vector size. Will it any problem if I use the size the large vector running the code?

Another thing is that, in the flat file I do not see two column, instead I see only one column and the entries coming from the vector vec2[i] . How to have both entries in the first column for the vec1, and for the second column for the vec2?


Solution

  • C++ does not allow to read from a vector past its last element. Full stop. If you use the at method, you will get an out_of_range exception, and with the [] operator you just experience undefined behaviour.

    That means that you will have to check the size of the vector. You code could become:

    #include <fstream>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    //int main()
    void ffile()
    {
        // std::ofstream ofs;     // unused 
        ofstream outFile;
        outFile.open("flatFile.dat");
        vector<int> vec1{ 10, 20 };
        vector<int> vec2{ 0, 20, 30 };
    
        // use the sizes of both vectors to compute the loop limit
        for (unsigned i = 0; i <= std::max(vec1.size(), vec2.size()); i++)
    
        {
            if (i < vec1.size()) outFile << vec1[i];  // only output actual values
            outFile << "\t";
            if (i < vec2.size()) outFile << vec2[i];
            outFile << endl;
        }
    }
    

    This code should give a text file similar to:

    0   0
    20  20
        30
    

    (it did in my tests...)