程序结束时“损坏”

时间:2011-03-12 18:05:09

标签: c++ class

嘿,我执行它后的代码说“帐户”已经损坏......

这是什么意思,我该如何解决?

#include <iostream>
#include <iomanip>

using namespace std;

class BankAccount
{
private:
    int accountNum;
    double accountBal;
    const static double annualIntRate;
public:
    void enterAccountData(int, double);
    //void computeInterest();
    //void displayAccount();
};

// implementation section:
//const double BankAccount::annualIntRate = 0.03;
void BankAccount::enterAccountData(int number, double balance)
{
    cout << setprecision(2) << fixed;
    accountNum = number;
    accountBal = balance;

    cout << "Enter the account number " << endl;
    cin >> number;

    while(number < 0 && number <= 999)
    {
        cout << "Account numbers cannot be negative or less than 1000 " <<
                "Enter a new account number: " << endl;
        cin >> number;
    }

    cout << "Enter the account balance " << endl;
    cin >> balance;

    while(balance < 0)
    {
        cout << "Account balances cannot be negative. " <<
                "Enter a new account balance: " << endl;
        cin >> balance;
    }
    return;
}
/*void BankAccount::computeInterest()
{

}*/

int main()
{
    const int QUIT = 0;
    const int MAX_ACCOUNTS = 10;
    int counter;
    int input;
    int number = 0;
    double balance = 0;

    BankAccount accounts[MAX_ACCOUNTS];
    //BankAccount display;
    do
    {
        counter = 0;
        accounts[MAX_ACCOUNTS].enterAccountData(number, balance);
        cout << " Enter " << QUIT << " to stop, or press 1 to proceed.";
        cin >> input;
        counter++;
    } while(input != QUIT && counter != 10);

    system("pause");
    return 0;
}

2 个答案:

答案 0 :(得分:4)

accounts[MAX_ACCOUNTS].enterAccountData(number, balance);

大概你的意思是:

accounts[counter].enterAccountData(number, balance);

accounts[MAX_ACCOUNTS]不存在:accounts数组中包含MAX_ACCOUNTS个元素,并且它们从零开始编制索引。你还需要在循环之外移动counter的初始化,否则你根本就没有计算任何东西!

另请注意,您的输入处理不正确。如果您在提示输入新帐号时输入hello,则程序将停止运行,因为您未检查the state of the stream以确保提取成功。 C ++中的惯用语输入操作如下所示:

int number;
if (!(std::cin >> number)) {
    // o noez! The user didn't type in a number at all! Handle the error here...
}

处理错误时,如果要继续从流中读取,则需要使用其clear()成员函数重置状态标志及其ignore()成员函数以跳过输入无效。

处理控制台输入时,通常更容易将字符串读入std::string,然后使用std::stringstream解析字符串;这样可以实现更简单,更直接的错误处理,因为您无需处理std::cin中的无效字符清除,您只需丢弃std::stringstream并轻松重新开始。

答案 1 :(得分:2)

enterAccountData()中,当您使用accounts[MAX_ACCOUNTS]时,您正在使用accounts[counter]

MAX_ACCOUNTS索引超出了数组的范围(一个),当你检索它时会导致不可预测的行为(它将在数组后立即读取内存中的内容并尝试将其变为{{{ 1}} object)。

此外,由于您在循环内初始化BankAccount为0 ,因此每次都会重新启动;你希望在循环开始之前将初始化移动到