Lucy Loo - 1 year ago 91
C++ Question

# Trying to write to file but only prints once

I'm writing a small physics engine and I'm learning how to write to a file, what I want to do is print the angle to the

`angle.txt`
file the same way it does on output. Here's my program:

``````int main() {

ofstream myFile;
myFile.open("angle.txt");

cout << "Insert a lanuch Angle (theta): ";
cin >> thetaDegrees;
cout << "Insert a launch height: ";
cin >> yOld;
cout << "Insert an initial velocity: ";
cin >> initialVelocity;
cout << "Time (DeltaT) in seconds: ";
cin >> totalT;

for (double deltaTime = 0.0; deltaTime < totalT; deltaTime += 0.1) {

const double squared = deltaTime * deltaTime;       // squared constant for deltaTime squared

theta = thetaDegrees * PI / 180;    // converts theta to a degrees value

// apply initialV to velocity
velocity = initialVelocity + 9.8 * time;

yNew = yOld + velocityY * deltaTime - gravitiyHalf * (squared); // calculates Y

velocityY = velocity - 9.8 * deltaTime; // includes gravity to Y

angle = atan2(yNew, xNew) * 180 / PI;   // convert angle to degrees

this_thread::sleep_for(chrono::seconds(1));     // sleeps for 1 second each loop

cout << "\nHeight: " << yNew << endl;
cout << "Angle: " << angle << endl;
myFile << angle;    // it displays the first value but nothing else!
myFile.close();

yOld = yNew;
}

}
``````

When I run this program, the file only shows the first value of angle to the file, after that it ignores the rest. How can I fix this so the
`angle.txt`
file shows every value of angle?

EDIT: I have also tried using
`myFile.close();`
outside of the for loop but that doesn't work.

Answer Source

Streams are usually buffered. One consequence of this is that characters written to the stream do not appear in the destination until the buffer is flushed.

If you do not do anything to flush the buffer, then written characters will not appear until the buffer gets filled up, which will take a rather long time given the rate at which you write to file.

You need to do one of the following:

``````// Option 1
myFile << angle << flush;

// Option 2
myFile << angle;
myFile.flush();
``````

If you actually mean for each output to be on a separate line and you just forgot to write out the newlines, then there's yet another option, since this is precisely the use case that `endl` is meant for:

``````// Option 1
myFile << angle << endl;

// Option 2
myFile << angle << '\n' << flush;

// Option 3
myFile << angle << '\n';
myFile.flush();
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download