簡體   English   中英

變量周圍的堆棧已損壞

[英]Stack around the variable is corrupted

我有一個非常簡單的初學者問題,我必須缺少一些顯而易見的東西。 我只是試圖提示用戶輸入一個4位數字,然后將輸入作為數組輸入,將這些數字單獨分割。 我認為這與“ cin >> input [4]”有關,我似乎無法獲得正確的答案。

int main()
{
int input[4];       //number entered by user
cout << "Please enter a combination to try for, or 0 for a random value: " << endl;
cin >> input[4];
}

當我運行它時,收到一條錯誤消息“變量周圍的堆棧已損壞。我嘗試在其他問題中查看類似的示例,但似乎無法正確理解。我需要輸入一個4位數字然后將其拆分為4位數組。如果有人可以提供幫助,我將不勝感激。

您的數組大小為4,因此元素的索引為0 .. 3; input [4]位於數組末尾,因此您嘗試修改未分配或分配給其他內容的內存。

這將為您工作:

cin >> input[0];
cin >> input[1];
cin >> input[2];
cin >> input[3];

您無需輸入任何4位數字即可進入。

int in;
int input[4];
cin >> in;

if(in>9999 || in < 1000) {
   out << "specify 4 digit number" << endl;
   return;
}
input[0] = in%1000;
input[1] = (in-1000*input[0])%100;
input[2] = (in-1000*input[0]-100*input[1])%10;
input[3] = in-1000*input[0]-100*input[1]-input[2]*10;

問題是您試圖讀取一個不存在的字符 (索引4處的字符 )。如果將input聲明為int input[4]; ,則索引4處沒有任何字符; 僅索引0 ... 3有效。

也許您應該只使用std::stringstd::getline() ,然后可以根據需要將用戶輸入解析為整數。 或者你可以嘗試

std::cin >> input[0] >> input[1] >> input[2] >> input[3];

如果可以忍受數字必須用空格分隔的約束。

這包括一些錯誤檢查:

int n = 0;
while( n < 1000 || n >= 10000 ) // check read integer fits desired criteria
{
    cout << "enter 4 digit number: ";
    cin >> n;   // read the input as one integer (likely 10 digit support)
    if( !cin.good() )   // check for problems reading the int
        cin.clear();    // fix cin to make it useable again
    while(cin.get() != '\n'); // make sure entire entered line is read
}
int arr[4];  // holder for desired "broken up" integer
for( int i=0, place=1; i<4; ++i, place *= 10 )
    arr[i] = (n / place) % 10;    // get n's place for each slot in array.
cout << arr[3] << " " << arr[2] << " " << arr[1] << " " << arr[0] << endl;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM