How to create a txt file from FOR loop?

243 Views Asked by At

I wrote a C++ code using iterative methods. For this, I used a FOR loop. However, I need to save every result by iteration in same text file (or DATA file) as a columns. How can I do it? Thanks for your advices.

This a simple version of my code:

#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
int i;
main()
{
cout<<"Value 1"<<right<<setw(20)<<"Value 2"<<endl;
for(i=0;i<5;i++)
{
cout<< left << setw(20) << i+10
    << setw(20) << i<<endl;
}
getch();
}
1

There are 1 best solutions below

0
On BEST ANSWER

For most purposes using a CSV file would be better. Here is a code that does what you need.

#include <stdio.h>
int main() {
  FILE * fpw; // A file pointer/handler that can refer to the file via a cpp variable
  fpw = fopen("data.txt", "w"); // Open the file in write("w" mode

  if (fpw == NULL) {
    printf("Error"); // Detect if there were any errors
    return 0;
  }

  fprintf(fpw, "Value 1,Value 2\n"); // Write the headers 
  int i = 0;
  for (i = 0; i < 5; i++) {
    fprintf(fpw, "%d,%d\n", i + 10, i); // Write the values
  }
  fclose(fpw); //Don't forget to close the handler/pointer

  return 0;
}

Output: A file data.txt will be created with following contents:

Value 1,Value 2
10,0
11,1
12,2
13,3
14,4