Search code examples
c++fstream

How do I append data in columns?


The following code appends the values of y[i] in the same column as x[i], y[0] starting underneath x[10]. I would like to append the values of y[i] in the second column next to the first column of the values of x[i]. Could you please help me how to do this?

#include <fstream>
using namespace std;
int main() {
  ofstream outfile;
  double x[10], y[10];
  for(int i=0; i<10; i++){
    x[i] = i+10;
  }
  for(int i=0; i<10; i++){
    y[i] = i-10;
  }
  outfile.open("result.txt", ios_base::app);
  outfile << "loop: " << 1 << endl;
  for(int i=0; i<10; i++){
  outfile << x[i] << "\n";
  }
  outfile << "loop: " << 2 << endl;
  for(int i=0; i<10; i++){
    outfile << y[i] << "\n";
  }
  outfile.close();
return 0;
}

Solution

  • Change

    outfile << "loop: " << 1 << endl;
     for(int i=0; i<10; i++){
       outfile << x[i] << "\n";
     }
    

    To-

    outfile << "loop: 1 \t loop: 2"  << endl;
     for(int i=0; i<10; i++){
    outfile << x[i] << " \t "<<y[i]<<"\n";
    }
    

    No need for

    outfile << "loop: " << 2 << endl;
      for(int i=0; i<10; i++){
      outfile << y[i] << "\n";}