user2921180
user2921180

Reputation: 11

Stack around the variable is corrupted

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.

Upvotes: 0

Views: 556

Answers (3)

user645280
user645280

Reputation:

This includes a small bit of error checking:

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;

Upvotes: 0

ChatCloud
ChatCloud

Reputation: 1190

Your array is of size 4, so elements have indicies 0 .. 3; input[4] is located behind the end of your array so you are attemping to modify memory not allocated or allocated for other stuff.

This will work for you:

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

You do not need an arry to input 4 digit number.

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;

Upvotes: 2

user529758
user529758

Reputation:

The problem is that you are trying to read in a character that does not exist (the one at index 4).If you declare input as int input[4];, then it doesn't have any characters at index 4; only indices 0...3 are valid.

Perhaps you should just use an std::string and std::getline(), and you could then parse the user input to integers however you like. Or you can try

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

if you can live with the constraint that the numbers must be whitespace-separated.

Upvotes: 1

Related Questions