变量周围的堆栈已损坏

时间:2013-10-25 18:48:45

标签: c++ arrays cin

我有一个看起来非常简单,初学者的问题,我必须忽略一些显而易见的事情。我只是试图提示用户输入一个4位数字,然后将输入作为一个数组接收,将数字拆分为自己。我认为它与“cin>>输入[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位数组。 如果有人能提供帮助我会非常感激。

3 个答案:

答案 0 :(得分:2)

您的数组大小为4,因此元素的标记为0 .. 3; input [4]位于数组末尾的后面,因此您正在尝试修改未分配或分配给其他内容的内存。

这对你有用:

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

您不需要arry输入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;

答案 1 :(得分:1)

问题在于您尝试在不存在的字符中读取 (索引为4的那个)。如果您将input声明为int input[4];,那么它在索引4处没有任何字符;只有索引0 ... 3有效。

也许您应该使用std::stringstd::getline(),然后您可以根据需要将用户输入解析为整数。或者你可以尝试

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

如果你能忍受数字必须用空格分隔的约束。

答案 2 :(得分:0)

这包括一些错误检查:

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;