如何在列中附加数据?

时间:2017-03-21 03:14:29

标签: c++ fstream

以下代码将y [i]的值与x [i],y [0]在x [10]下面的相同列中追加。我想在x [i]的值的第一列旁边的第二列中追加y [i]的值。你能帮帮我怎么做吗?

#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;
}

2 个答案:

答案 0 :(得分:0)

你想这样做吗?

#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;
    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] << ' ' << y[i] << "\n";
  }
  outfile.close();
  return 0;
}

答案 1 :(得分:0)

更改

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

要 -

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

不需要

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