2012-10-22 49 views
-2

每當我的程序循環存儲在int array[]內部的數據都被清除。在循環中,數組總是被清除

當用戶選擇第一個選項時,我每做一次count和count2檢查,但它正在重置而不是增量。

#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; 
} 
+1

你是指在函數內聲明的數組嗎?每次調用函數時都會創建並銷燬它們。這就是局部變量應該如何工作。 –

+0

@ bo-persson我的數組是在MissionPlan()構造函數裏面創建的,如果是這樣的話,我該如何分割它以使它成爲全局的?也是我的計數器,我需要它能夠在整個程序中循環,而不需要重新設置。 :( –

回答

4

你在函數MissionPlan()中聲明你的數組,使它們在堆棧下。當函數返回(退出)時,不能保證數組將被保留,並且它們很可能會被「重新初始化」,即歸零。

如果您需要保留數組的內容,有幾個選項,其中之一是宣佈在全球範圍內(即以外的所有功能)的陣列,另一個是將static修改添加到數組變量,使得所述陣列被只有一次初始化,它的內容將被保持在整個程序:

static int coor [100]; //storing x and y coordinates 
static float index[100];//storing the civ index 

還有一個選擇是聲明內部main()函數的變量,並通過函數參數傳遞它們。


我看見你在你的代碼中使用class但目前看來,你沒有正確使用它們:你只是不停地調用構造函數? (我很困惑它是否會起作用...)

我認爲在你的情況下,你會簡單地定義一個簡單的函數。或者如果你真的使用class,請將其實例保存在main()中,將數組和其他變量重複使用到class中,並使MissionPlan()成爲函數而不是構造函數。

+0

Ty靜態盈方似乎工作:D –

3

在每次迭代結束時,您使return將您拋出運行函數。 再次輸入函數時,所有局部變量都將重新初始化。將它們從功能體中取出。或者將main()的外部無限循環放入MissionPlan()

+0

如果我把我的循環出我的主要(),並做一個無限循環在我的MissionPlan()構造函數,當它結束時,它立即退出我的程序。 2無限循環在我的主要和我的構造函數。:/ –