I wrote a program that reads in a list of rocket names and masses and prints them in reverse order. The list should be terminated by the value "END". The value "END" is not part of the list and should not be printed out. The names are read into a string array and masses are read into a double array.
How do I terminate the list by the value "END"??
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
for (int i=0; i<4; i++)
{
cout << "Enter a rocket name (End to end list):";
cin >> rname[i];
cout << "What is the mass of " << rname[i] << ": ";
cin >> rmass[i];
}
cout << "The rockets entered in reverse order are:\n";
for (int i=4-1; i>=0; i--)
{
cout << rname[i] << setw(10) << rmass[i] << endl;
}
I tried a if statement right after the first input
But it also prints the rest of the rockets with crazy numbers. I think because of my for loop to output the rockets in reverse order.
This is the output:
Enter a rocket name (END to end list):rocket1
What is the mass of rocket1: 1
Enter a rocket name (END to end list):rocket2
What is the mass of rocket2: 2
Enter a rocket name (END to end list):rocket3
What is the mass of rocket3: 3
Enter a rocket name (END to end list):END
The rockets entered in reverse order are:
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
rocket3 3
rocket2 2
rocket1 1
Would you like to process another list? (Y or N) : reverse order.
What do I change in my for loop?
for(i= 51-1; i>=0; i--)
You need to keep a count of the number of rockets actually entered by the user seeing as the user could enter "END" without entering the full 51 rocket names.
1 2 3
for (int i = num_entered - 1; i >= 0; i--) {
...
}