0

I have what seems like a pretty simple, beginner question that I must be missing something obvious. I am just trying to prompt the user to input a 4 digit number and then take in the input as an array, splitting up the digits to be by themselves. I thought it hade something to do with "cin >> input[4]" I just can't seem to get the right answer.

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];
}

When I go to run it, I get an error message "Stack around the variable was corrupted. I tried looking at similar examples in other questions but I just can't seem to get it right. I need the input as one 4 digit number and then split it up to a 4 position array. If anyone could help I would greatly appreciate it.

4

3 回答 3

2

您的数组大小为 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;
于 2013-10-25T18:54:41.110 回答
1

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

也许您应该只使用std::stringand std::getline(),然后您可以将用户输入解析为您喜欢的整数。或者你可以试试

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

如果您可以忍受数字必须以空格分隔的约束。

于 2013-10-25T18:55:26.707 回答
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;
于 2013-10-25T20:05:20.890 回答