gpt4 book ai didi

c++ - "corrupted"程序结束

转载 作者:行者123 更新时间:2023-11-30 00:58:57 26 4
gpt4 key购买 nike

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

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

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

最佳答案

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 轻松重新开始。

关于c++ - "corrupted"程序结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5284378/

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