While loop within a while loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
/* This program will compute the temperature of a gas using the gas law.*/
#include<iostream>
#include<fstream>
#include<iomanip>
#include<cmath>
using namespace std;
int main()
{
double velocity, time, distance, counter = 1, a;
ifstream infile ("R:distanceIn.txt");
ofstream outfile ("C:distanceOut.txt");
if (infile.fail())
{
cout << "Error. Unable to read file" << endl;
return 0;
}
else
{
outfile << " Car under constant acceleration" << endl;
outfile << "\n" << setw(8) << "Initial Velocity " << "Time " << "Acceleration " << "Distance " << endl;
while (counter < 3 && !infile.eof())
{
infile >> velocity >> time;
while ( counter < 6 && !infile.eof())
{
infile >> a;
distance = velocity + 0.5 * (a*(pow(time,2)));
outfile << setw(7) << velocity << setw(16) << time <<setw(13)<< a<<setw(18)<< distance;
outfile << endl;
counter++;
}
counter++;
}
infile.close();
}
return 0;
}
|
Trying to do a while loop within another while loop. The one within works, but the main while loop goes through only once.
Here are the data from my input and output files:
distanceIn.txt
10 5
3
4
5
6
7
5 10
3
4
5
6
7
----------------------------------------------------------------------------
distanceOut.txt
Car under constant acceleration
Initial Velocity Time Acceleration Distance
10 5 3 47.5
10 5 4 60
10 5 5 72.5
10 5 6 85
10 5 7 97.5
|
The inner loop exits when "counter" is greater then or equal to 6. By the time the outer loop evaluates "counter" again it has to be greater then 3.
I got it. I ended up using a for loop then a nested for loop, and it worked. Thanks.
Topic archived. No new replies allowed.