-
Simple Array Program
So i have to read in a list of rocket names and masses and print them out the rocket names and masses in the reverse order they were entered. The list is terminated by the value "END". However, "END" should not be part of the list and should not be printed out. Max number of rockets is 50. Where do I go from here?
Code:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
// Main Program
int main( )
{
// Constant Declarations
// Variable Declarations
string r_names [50];
double mass[50];
int i;
string junk;
for(i = 0; i < 49; i++)
{
cout << "Enter a rocket name (END to end list): ";
getline(cin, r_names[i]);
if(r_names[i] != "END")
{
cout << "What is the mass of a " << r_names[i] << ": ";
cin >> mass[i];
getline(cin, junk);
}
if(r_names[i] == "END")
{
break;
}
}
cout << "The rocket's entered in reverse order are:"
<< r_names[i] << setiosflags(ios::fixed) << setw(6)
<< mass[i] << endl;
cout << "\n\nEnd Program.\n";
return 0;
}
-
Does the code compile without errors/warnings?
If not post the complete error/warning message exactly as it appears in your development environment.
If it does compile without errors, does it produce the desired output?
If not what output does the program produce? What do you expect the output to be?
Jim
-
This will not read 50:
Code:
for(i = 0; i < 49; i++)
Go for
Code:
for(i = 0; i < sizeof(r_names)/sizeof(r_names[0]); i++)
Code:
getline(cin, r_names[i]);
Simple logic! Read into a separate variable and compare that to "END", and only add to the r_names array if it's not "END".
-
Jim: The program prints out with no compiler errors:
The rocket's entered in reverse order are:END
-9255963134931783000000000000000000
0000000000000000000000000000.000000.
The string, if that's the correct term usage, END will end the list and place the rocket names and masses in reverse order.
For example, I will enter:
Alpha
62
Omega
35
Delta
39
END
The rockets entered in reverse order are:
Delta 39
Omega 35
Alpha 62
Rags_to_riches: I do not understand the purpose of the second part with your modified version of the for loop. What will that do?
-
The loop as you've written it will only gather up to 49 entries, not the 50 you need. As I have written it, it will gather the number of entries that will fit in the array; that is, 50 entries, as specified. sizeof() returns the size of the variable given. In this case the size is 50 * the size of a string variable. Therefore, in order to get the number of entries in the array you must divide that value by the size of a string variable.
-
rags_to_riches: Can you elaborate on the statement you made and possibly give an example?
Simple logic! Read into a separate variable and compare that to "END", and only add to the r_names array if it's not "END".
-
I finally got the program to work. Thank you for the help!