Hi there.
The problem that I'm experiencing here is quite a specific one, and after a few searches, I concluded that I ought to just ask. Tbh, I'm a little bit unsure what to search exactly!

I have calculated earlier in my program various values in various arrays, angle[], t[], y[], x[] etc and now I want to output these values in table form to a text file. Because these arrays contain different values I have introduced a while loop which I thought would write one row of the table "num" times, changing the value of x[1] to x[2] etc every time it loops.

This isn't happening however, and the only thing being written to file is the table header shown on lines 5-7 below. It seems as if the while loop and everything inside it is being ignored completely!
Am I missing something really obvious here?

What is bugging me even more is the fact that I used the same while loop method to cout the same table to be viewed inside my program by the user and this works fine. (This code is shown further down the page).

This is a problem that is really holding back the progress with my project and any help would be greatly appreciated!
Many thanks, Robin.

Writing to file code.

ofstream myfile;


myfile << setw(20) << "number" << setw(20) << "Angle (rads)" << setw(20) << "Time (s)" << setw(20) << "Max height (m)" << setw(20) << "Max distance (m)" << endl;

while (n < num)

myfile << setw(20) << n << setw(20) << angle[n] << setw(20) << t[n] << setw(20) << y[n] << setw(20) << x[n] << endl;



cout << "End the program and view the output file or try new \n"
<< "values of u and theta \n"
<< "...." << endl;

cout code.

cout << setw(10) << "number" << setw(15) << "Angle (rads)" << setw(15) << "Time (s)" << setw(15) << "Height (m)" << setw(15) << "Distance (m)" << endl;

while (m < num)

cout << setw(10) << m << setw(15) << angle[m] << setw(15) << t[m] << setw(15) << y[m] << setw(15) << x[m] << endl;
8 Years
Discussion Span
Last Post by Ancient Dragon

two things
1) what is the value of n before that loop starts? Uninitialized variable is the most likely reason the data is not being written to the file. Add n = 0; on line 6 and see if that doesn't fix the problem.

2: The code is not writing the first row in those arrays because the index counter is being incremented before the write. Arrays are numbered 0 to whatever, not 1 to whatever. Move line 9 down after line 11.

Edited by Ancient Dragon: n/a


Thanks for the advice!
Since posting I replaced lines 7-12 with a for loop stating n = 0;

for (n = 0; n <= num; ++n)

It now works.

Much appreciated, thankyou.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.