0
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

int main() {
   bool done = false;
   cout << setprecision(20) << endl;
    ifstream infile("in.txt");
    ifstream outfile("out.txt");
    while(!infile.eof()) {
           int sign = 1;
           double pi = 0;
           long n;
           infile >> n;

           for(long i = 1; i < n; i += 2) {
               pi += sign/(double)i;
               sign = -sign;
           }
           pi *= 4;
           cout << "value of pi for n = " << n << " is " << pi << endl;

       }


   return 0;
}

This reads from a file and prints to the console but I can't get the code to print to the outfile. I've tried doing

outfile<< "value of pi for n = " << n << " is " << pi << endl;

But that doesn't seem to work

  • 1
    you should define "ofstream" outfile("out.txt"); instead of "ifstream" outfile("out.txt"); – samini Mar 02 '20 at 05:09
  • You will want to review [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – David C. Rankin Mar 02 '20 at 05:15

1 Answers1

1

It does not write to the file because you defined outfile as an std::ifstream ifstream is for input files. Define it as an ofstream and it should work.

Example:

ofstream outfile("out.txt");
Andrew Truckle
  • 13,595
  • 10
  • 45
  • 105
Kevin
  • 463
  • 1
  • 7
  • 20