gpt4 book ai didi

c++ - 变量周围的堆栈已损坏

转载 作者:行者123 更新时间:2023-11-28 00:39:22 25 4
gpt4 key购买 nike

我有一个看似非常简单的初学者问题,我一定遗漏了一些明显的东西。我只是想提示用户输入一个 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;

关于c++ - 变量周围的堆栈已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19597353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com