2012-03-06 228 views
4

我有一個循環,直到經修正Y的功能,正回答類型,但在選擇結束時,我得到的錯誤:堆棧被損壞

Time Check Failure #2 - Stack around the variable 'YESNO' was corrupted. 

香港專業教育學院對谷歌一看,着真的找到任何relivent回答這個錯誤我的代碼如下:

void Mesh_equations(float a,float b,float c,float d,float e,float f){ 

    char YESNO[1];                     //define variables. 
    int loop=0;                     //loop set to zero. 
    while(loop==0){                    //while loop initiated whilst loop is equal to zero. 
    cout <<"\nDo you want to display your coefficients for the mesh equations...(y/n)?"; 
    cin>>YESNO;                     //prompt and cin. 
    if (YESNO[0] == 'Y' || YESNO[0] == 'y'){               //if cin is 'Y' or 'y' 
     system("CLS"); 
     cout<<"Loop One:\n(" <<a <<")" <<"Ix + (" <<b <<")" <<"Iy = (" <<e <<")" <<endl 
      <<"Loop Two:\n(" <<c <<")" <<"Ix + (" <<d <<")" <<"Iy = (" <<f <<")" <<endl<<endl 
      <<setw(5)<<" Where ;\n" 
      <<setw(5)<<"A ="<<a<<endl 
      <<setw(5)<<"B ="<<b<<endl 
      <<setw(5)<<"C ="<<c<<endl 
      <<setw(5)<<"D ="<<d<<endl 
      <<setw(5)<<"E ="<<e<<endl               ////set the field width to 5 characters. 
      <<setw(5)<<"F ="<<f <<endl<<endl;             //display. 
     loop=1;                     //loop is 1, while loop passed. 
     system("pause"); 
    } 
    else if(YESNO[0] == 'N' || YESNO[0] == 'n'){              //if 'N' or 'n', while loop passed. 
    loop=1; 
    } 
    else{                      //if neither y or n is enterred input must be incorrect. 
    cout <<"bad answer, try again\n"; 
    Beep (600,100); 
    loop=0;                      //loop is zero, while loop continues. 
    } 
} 
} 

感謝 Houlahan。

回答

4

發生這種情況是因爲YESNO是一個字符數組,而cin >> YESNO;正在向此數組寫入NULL終止符。

將YESNO的聲明更改爲char YESNO;,並刪除數組運算符,並且您很好。

1

使YESNO變大,即10個字符而不是1.空字符放在數組中的最後一個允許位置之後,這是錯誤的原因。

+0

這不會防止腐敗如果有人輸入更長的響應時間...嘗試使用字符串,而不是http://www.cplusplus.com/reference/string/string/ – Poodlehat 2012-03-06 20:04:23

+1

我同意,輸入可以實際上限制使用setw像:cin >> setw(3)>> YESNO; to allo是,No等 – marcinj 2012-03-06 20:09:08

2

如果數組元素被分配到數組的邊界之外,那麼在運行時會顯示消息「堆棧變量已損壞」。因此,要解決此問題,請確保分配的數組大小和分配給它的值。

+0

「越界」可能是由「cin >> YESNO」引起的,因爲這意味着「讀取字符串」。你應該做「cin >> YESNO [0]」。 – mikijov 2012-10-02 18:37:51

+0

你回答我很多...我試圖從昨天解決問題..但不能......感謝很多.. – MMH 2012-10-18 02:13:16