user3257023
user3257023

Reputation: 43

Trying to setup an array to store the last three deposits into bank account system

float deposit (float balance)
{
    float amount[3]; 
    system("cls");
    cout<<"Enter the amount you wish to deposit"<<endl; 
    cin>>amount[3]; 
        balance = balance + amount[3]; 
    writeBalance(balance); 
    return balance;  
}
//This is a function to allow the user to increase their balance 

but when I enter an amount in the deposit section of the program a popup box comes up and says:

Run-Time Check Failure #2 - Stack around the variable 'amount' was corrupted.

any help would be great thanks

Upvotes: 0

Views: 373

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

You must enter each element of the array in a loop. Change the code the following way

float deposit (float balance)
{
    const size_t N = 3; 
    float amount[N]; 
    system("cls");
    cout<<"Enter the amount you wish to deposit"<<endl;

    for ( size_t i = 0; i < N; i++ )
    { 
        cin>>amount[i]; 
        balance = balance + amount[i];
    }

    writeBalance(balance); 
    return balance;  
}

Though in fact there is no need to use the array. You could enter data in one regular variable.

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234845

Since you have float amount[3];, you can only access amount[0], amount[1], and amount[2]. Any other index with give you undefined behaviour which is the cause of your program crash.

Also, never use a float to represent actual money. You'll only be accurate to about 7 significant figures. Using a double is unsafe too even though the accuracy (at around 15 significant figures) will be better. Your best bet is to use a currency type. Have a look at this question: Best way to store currency values in C++

Upvotes: 2

Related Questions