Each time my program loops the data which is stored inside an int array[] is being cleared.
I did a count and count2 check every time it goes when the user selects the 1st option, but it is getting reset instead of the increment too.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class MissionPlan //start of MissionPlan class
{
public:
MissionPlan();
}; //end of MissionPlan class
MissionPlan::MissionPlan()
{
int choice; // to capture what user inputs into menu
int count=0; // to count how many times it save into array and use it later for looping
int count2=0;//for adding x and y coordinates correctly into array
int coor [100]; //storing x and y coordinates
float index[100];//storing the civ index
cout<<"Welcome to Mission Plan program!"<<endl<<endl<<"1) Input statistical data"<<endl<<"2) Compute civ.index value(for all records)"<<endl<<
"3) Print top 5 exploration destinations"<<endl<<"4) Print total travel distance"<<endl<<endl<<"Please enter your choice: ";
cin>>choice;
for(;;)
{
if(choice == 1)
{
cout<<count<<endl;
cout<<count2<<endl;
int x,y; // for reading x and y coordinate
cout<<"Please enter x-ordinate: "; //Display x-ordinate
cin>>x;//reading input from user and put into x
coor[count2] = x;//storing x coordinate into coor[] array
cout<<"Please enter y-ordinate: ";//Display y-ordinate
cin>>y;//reading input from user and put into x
coor[1+count2] = y;//storing y coordinate into coor[] array
cin.clear();//clearing cin
cin.ignore(10000,'\n');//to ignore char to 10000 and a linefeed
count++;
count2 +=2;
cout<<count<<endl;
cout<<count2<<endl;
return;
}
else if(choice == 2)
{
cout<<"choice 2 "<<endl;//to display
return;
}
else if(choice==3)
{
cout<<"choice 3"<<endl;
return;
}
else
cout<<"Please enter number 1 to 4 only!"<<endl;
}//end of while loop
}//end of MissionPlan()
int main()
{
for(;;)
{
MissionPlan();
}
return 0;
}
You declared your arrays inside the function
MissionPlan(), so that they are under the stack. When the function returns (exited), there is no guarantee that the arrays will be kept, and they will most probably be “re-initialized”, that’s zeroed.If you need to preserve the content of the arrays, there are a few options, one of them is to declare the array in the global scope (i.e. outside all functions), another is to add the
staticmodifier to the array variable so that the array is initialized only once and its content will be kept throughout the program:One more option is to declare the variable inside
main()function and pass them by function parameters.I saw you used
classin your code but seems that you’re not using them appropriately: you just kept calling the constructor? (which I am quite confused whether it will work…)I think in your case you would simply define a simple function. Or if you really use
class, keep an instance of it inmain(), put the arrays and other variables that will be reused into theclass, and makeMissionPlan()a function instead of a constructor.