| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 639 人关注过本帖
标题:有人能看看我这个代码为什么内存不足吗
只看楼主 加入收藏
羽笙
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2023-6-3
结帖率:0
收藏
已结贴  问题点数:20 回复次数:3 
有人能看看我这个代码为什么内存不足吗
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <fstream>

using namespace std;

// 存储账户信息的结构体
struct AccountInfo {
    string name;
    string password;
    string phone;
    double balance;
    bool isLost;
};

// 存储交易记录的结构体
struct Transaction {
    string type;
    double amount;
    double fee;
};

class Account {
private:
    AccountInfo info;
    vector<Transaction> transactions;

public:
    Account(string name, string password, string phone, double balance) {
        info = {name, password, phone, balance, false};
    }
    ~Account() {}

    // 公有的交易记录访问接口
    const vector<Transaction>& get_transactions() const { return transactions; }

    // 存款
    bool deposit(double amount) {
        if (amount > 0) {
            info.balance += amount;
            Transaction t = {"Deposit", amount, 0};
            transactions.push_back(t);
            return true;
        }
        return false;
    }

    // 取款
    bool withdraw(double amount, double fee) {
        if (amount + fee <= info.balance && amount > 0 && fee >= 0) {
            info.balance -= (amount + fee);
            Transaction t = {"Withdraw", amount, fee};
            transactions.push_back(t);
            return true;
        }
        return false;
    }

    // 查询余额
    double getBalance() const {
        return info.balance;
    }

    // 查询交易记录
    void printTransactions() const {
        cout << "Transaction history:\n";
        for (const auto& t : transactions) {
            cout << "  " << t.type << " " << t.amount << " fee: " << t.fee << endl;
        }
    }

    // 判断账户是否挂失
    bool isLost() const {
        return info.isLost;
    }

    // 设置账户挂失状态
    void setLost(bool lost) {
        info.isLost = lost;
    }

    // 获取账户信息
    AccountInfo getInfo() const {
        return info;
    }
};

// 保存所有账户的信息,以文本文件的格式存储
void saveAccounts(const vector<Account>& accounts) {
    ofstream outfile("accounts.txt");
    for (const auto& acc : accounts) {
        outfile << acc.getInfo().name << " " << acc.getInfo().password << " "
                << acc.getInfo().phone << " " << acc.getInfo().balance << " "
                << acc.isLost() << endl;
    }
    outfile.close();
}

// 读取账户信息文件,返回所有账户信息
vector<AccountInfo> readAccountInfo() {
    vector<AccountInfo> accounts;
    ifstream infile("accounts.txt");
    while (true) {
        string name, password, phone, isLostStr;
        double balance;
        infile >> name >> password >> phone >> balance >> isLostStr;
        if (infile.eof()) break;
        bool isLost = (isLostStr == "1");
        AccountInfo info = {name, password, phone, balance, isLost};
        accounts.push_back(info);
    }
    infile.close();
    return accounts;
}

// 加载所有账户信息
vector<Account> loadAccounts() {
    vector<Account> accounts;
    vector<AccountInfo> accountInfos = readAccountInfo();
    for (const auto& info : accountInfos) {
        Account account(info.name, info.password, info.phone, info.balance);
        if (info.isLost) {
            account.setLost(true);
        }
        accounts.push_back(account);
    }
    return accounts;
}

// 保存交易记录,以文本文件的格式存储
void saveTransactions(const vector<Account>& accounts) {
    ofstream outfile("transactions.txt");
    for (const auto& acc : accounts) {
        const vector<Transaction>& transactions = acc.get_transactions();
        for (const auto& t : transactions) {
            outfile << acc.getInfo().name << " " << t.type << " " << t.amount << " " << t.fee << endl;
        }
    }
    outfile.close();
}

// 读取交易记录文件,返回所有交易记录
vector<Transaction> readTransactions() {
    vector<Transaction> transactions;
    ifstream infile("transactions.txt");
    while (true) {
        string name, type;
        double amount, fee;
        infile >> name >> type >> amount >> fee;
        if (infile.eof()) break;
        Transaction t = {type, amount, fee};
        transactions.push_back(t);
    }
    infile.close();
    return transactions;
}

// 加载所有交易记录
void loadTransactions(vector<Account>& accounts) {
    vector<Transaction> transactions = readTransactions();
    for (auto& acc : accounts) {
        for (const auto& t : transactions) {
            string name = acc.getInfo().name;
            if (t.type == "Deposit" && name == acc.getInfo().name) {
                acc.deposit(t.amount);
            } else if (t.type == "Withdraw" && name == acc.getInfo().name) {
                acc.withdraw(t.amount, t.fee);
            }
        }
    }
}

int main() {
    // 加载账户和交易记录
    vector<Account> accounts = loadAccounts();
    loadTransactions(accounts);

    // 输出菜单
    cout << "Menu:\n"
         << "  1. Create new account.\n"
         << "  2. Close account.\n"
         << "  3. Report lost.\n"
         << "  4. Deposit.\n"
         << "  5. Withdraw.\n"
         << "  6. Query balance.\n"
         << "  7. Transaction history.\n"
         << "  8. Exit.\n";

    while (true) {
        int choice;
        cout << "Please enter your choice: ";
        cin >> choice;

        if (choice == 1) { // 开户
            string name, password, phone;
            double balance;
            cout << "Please enter your name: ";
            cin >> name;
            cout << "Please enter your password: ";
            cin >> password;
            cout << "Please enter your phone: ";
            cin >> phone;
            cout << "Please enter the initial deposit amount: ";
            cin >> balance;

            Account account(name, password, phone, balance);
            accounts.push_back(account);
            saveAccounts(accounts);
        } else if (choice == 2) { // 销户
            string name;
            cout << "Please enter your name: ";
            cin >> name;

            for (auto it = accounts.begin(); it != accounts.end(); ++it) {
                if (it->getInfo().name == name) {
                    accounts.erase(it);
                    break;
                }
            }
            saveAccounts(accounts);
        } else if (choice == 3) { // 挂失
            string name;
            cout << "Please enter your name: ";
            cin >> name;

            for (auto& acc : accounts) {
                if (acc.getInfo().name == name) {
                    acc.setLost(true);
                    break;
                }
            }
            saveAccounts(accounts);
        } else if (choice == 4) { // 存款
            string name;
            double amount;
            cout << "Please enter your name: ";
            cin >> name;

            auto it = find_if(accounts.begin(), accounts.end(), [&](const Account& acc) {
                return acc.getInfo().name == name;
            });
            if (it == accounts.end()) {
                cout << "Account does not exist.\n";
            } else if (it->isLost()) {
                cout << "Account is lost.\n";
            } else {
                cout << "Please enter the deposit amount: ";
                cin >> amount;
                if (it->deposit(amount)) {
                    saveTransactions(accounts);
                    cout << "Deposit successful.\n";
                } else {
                    cout << "Deposit failed.\n";
                }
            }
        } else if (choice == 5) { // 取款
            string name;
            double amount, fee;
            cout << "Please enter your name: ";
            cin >> name;

            auto it = find_if(accounts.begin(), accounts.end(), [&](const Account& acc) {
                return acc.getInfo().name == name;
            });
            if (it == accounts.end()) {
                cout << "Account does not exist.\n";
            } else if (it->isLost()) {
                cout << "Account is lost.\n";
            } else {
                cout << "Please enter the withdraw amount: ";
                cin >> amount;
                cout << "Please enter the fee amount: ";
                cin >> fee;
                if (it->withdraw(amount, fee)) {
                    saveTransactions(accounts);
                    cout << "Withdraw successful.\n";
                } else {
                    cout << "Withdraw failed.\n";
                }
            }
        } else if (choice == 6) { // 查询余额
            string name;
            cout << "Please enter your name: ";
            cin >> name;

            auto it = find_if(accounts.begin(), accounts.end(), [&](const Account& acc) {
                return acc.getInfo().name == name;
            });
            if (it == accounts.end()) {
                cout << "Account does not exist.\n";
            } else if (it->isLost()) {
                cout << "Account is lost.\n";
            } else {
                cout << "Your balance is: " << it->getBalance() << endl;
            }
        } else if (choice == 7) { // 查询历史交易记录
            string name;
            cout << "Please enter your name: ";
            cin >> name;

            auto it = find_if(accounts.begin(), accounts.end(), [&](const Account& acc) {
                return acc.getInfo().name == name;
            });
            if (it == accounts.end()) {
                cout << "Account does not exist.\n";
            } else {
                it->printTransactions();
            }
        } else if (choice == 8) { // 退出程序
            cout << "Goodbye.\n";
            break;
        } else { // 非法输入
            cout << "Invalid input. Please try again.\n";
        }
    }

    return 0;
}
运行出来就是现实内存不足,刚学没多久,求指点,拜托
搜索更多相关主题的帖子: amount cout const name string 
2023-06-03 20:34
apull
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
来 自:三体星系
等 级:版主
威 望:216
帖 子:1479
专家分:9055
注 册:2010-3-16
收藏
得分:10 
3个ifstream后面判断一下是否正常打开,再读取
if (!infile.is_open()) return;
2023-06-04 11:02
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:528
帖 子:9007
专家分:53942
注 册:2011-1-18
收藏
得分:10 
还有
while (true) {
    ……
    if (…….eof()) break;
    ……
}
这种逻辑本身就是错误的,eof不等于就读取失败。

整个代码逻辑混乱,最严重的是 函数readTransactions 中丢掉了 name 信息,然后在 函数loadTransactions 中就开始瞎搞了。
2023-06-04 16:09
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:528
帖 子:9007
专家分:53942
注 册:2011-1-18
收藏
得分:0 
逻辑太乱,我随手写一个。因为没测试过(代码这么长,肯定会有错误的),因此仅供参考。

程序代码:
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <optional>
#include <string>
#include <string_view>
#include <vector>

// 存储账户基本信息
struct AccountInfo
{
    std::string name;
    std::string password;
    std::string phone;
    double balance;
    bool isLost;
};

// 交易记录
struct Transaction
{
    std::string type;
    double amount;
    double fee;
};

class Account
{
public:
    explicit Account( AccountInfo ai ) : info_{std::move(ai)}
    {
    }

    const AccountInfo& get_info() const noexcept
    {
        return info_;
    }

    const std::vector<Transaction>& get_transactions() const noexcept
    {
        return transactions_;
    }
    std::vector<Transaction>& get_transactions() noexcept
    {
        return transactions_;
    }

    // 挂失
    bool lost() noexcept
    {
        if( info_.isLost )
            return false;
        info_.isLost = true;
        return true;
    }

    // 存款
    bool deposit( double amount )
    {
        if( info_.isLost || amount<=0 )
            return false;
        info_.balance += amount;
        transactions_.emplace_back( "Deposit", amount, 0 );
        return true;
    }

    // 取款
    bool withdraw( double amount, double fee )
    {
        if( info_.isLost || amount<=0 || fee<0 || info_.balance<amount+fee )
            return false;
        info_.balance -= amount + fee;
        transactions_.emplace_back( "Withdraw", amount, fee );
        return true;
    }

private:
    AccountInfo info_;
    std::vector<Transaction> transactions_;
};

class AccountManage
{
public:
    AccountManage( std::string path_accounts, std::string path_transactions )
        : path_accounts_(std::move(path_accounts)), path_transactions_(std::move(path_transactions))
    {
        load_accounts();
        load_transactions();
    }

    Account* at( std::string_view name ) noexcept
    {
        auto itor = std::ranges::find_if( accounts_, [=](const auto& item){return item.get_info().name==name;} );
        return itor!=std::end(accounts_) ? &*itor : nullptr;
    }

    const Account* at( std::string_view name ) const noexcept
    {
        auto itor = std::ranges::find_if( accounts_, [=](const auto& item){return item.get_info().name==name;} );
        return itor!=std::cend(accounts_) ? &*itor : nullptr;
    }

    bool load_accounts()
    {
        accounts_.clear();

        std::ifstream infile( path_accounts_.c_str() );
        for( ; ; )
        {
            AccountInfo info;
            std::string isloststr;
            infile >> info.name >> info.password >> info.phone >> info.balance >> isloststr;
            if( !infile )
                break;
            info.isLost = isloststr=="1";
            accounts_.emplace_back( std::move(info) );
        }
        return !infile.fail();
    }
    
    bool save_accounts() const
    {
        std::ofstream outfile( path_accounts_.c_str() );
        for( const auto& acc : accounts_ )
        {
            const auto& info = acc.get_info();
            outfile << info.name << ' ' << info.password << ' '
                    << info.phone << ' ' << info.balance << ' '
                    << info.isLost << '\n';
        }
        return !outfile.fail();
    }

    bool load_transactions()
    {
        for( auto& acc : accounts_ )
            acc.get_transactions().clear();

        std::ifstream infile( path_transactions_.c_str() );
        for( ; ; )
        {
            std::string name;
            Transaction ta;
            infile >> name >> ta.type >> ta.amount >> ta.fee;
            if( !infile )
                break;
            Account* p = at( name );
            if( p )
                p->get_transactions().push_back( std::move(ta) );
        }
        return !infile.fail();
    }

    bool save_transactions() const
    {
        std::ofstream outfile( path_transactions_.c_str() );
        for( const auto& acc : accounts_ )
        {
            for( const auto& t : acc.get_transactions() )
                outfile << acc.get_info().name << ' ' << t.type << ' ' << t.amount << ' ' << t.fee << '\n';
        }
        return !outfile.fail();
    }

    bool 开户( AccountInfo info )
    {
        if( info.isLost || at(info.name) )
            return false;
        accounts_.emplace_back( info );
        save_accounts();
        return true;
    }

    bool 销户( std::string_view name )
    {
        auto itor = std::ranges::find_if( accounts_, [=](const auto& item){return item.get_info().name==name;} );
        if( itor == std::end(accounts_) )
            return false;
        accounts_.erase( itor );
        save_accounts();
        auto rng = std::ranges::remove_if( accounts_, [=](const auto& item){return item.get_info().name==name;} );
        accounts_.erase( rng.begin(), rng.end() );
        save_transactions();
        return true;
    }

    bool 挂失( std::string_view name )
    {
        Account* p = at( name );
        if( !p )
            return false;
        bool result = p->lost();
        save_accounts();
        return result;
    }

    bool 存款( std::string_view name, double amount )
    {
        Account* p = at( name );
        if( !p )
            return false;
        bool result = p->deposit(amount);
        save_transactions();
        return true;
    }

    bool 取款( std::string_view name, double amount, double fee )
    {
        Account* p = at( name );
        if( !p )
            return false;
        bool result = p->withdraw( amount, fee );
        save_transactions();
        return true;
    }

    std::optional<double> 查询余额( std::string_view name ) const noexcept
    {
        const Account* p = at( name );
        if( !p || p->get_info().isLost )
            return {};
        return p->get_info().balance;
    }

    std::optional<std::string> 查询历史交易记录( std::string_view name, std::string_view leading="" ) const
    {
        const Account* p = at( name );
        if( !p || p->get_info().isLost )
            return {};

        std::ostringstream os;
        for( const auto& acc : accounts_ )
        {
            for( const auto& t : acc.get_transactions() )
                os << leading << t.type << "amount:" << t.amount << " fee:" << t.fee << '\n';
        }
        return os.str();
    }

private:
    std::string path_accounts_;
    std::string path_transactions_;
    std::vector<Account> accounts_;
};

using namespace std;

struct inputline
{
    std::string inputtip;

    explicit inputline( std::string inputtip ) noexcept : inputtip{std::move(inputtip)}
    {
    }

    operator std::string() const
    {
        return convert_<std::string>();
    }
    operator int() const
    {
        return convert_<int>();
    }
    operator double() const
    {
        return convert_<double>();
    }

private:
    template<typename T>
    T convert_() const
    {
        std::remove_cvref_t<T> value;
        for( ; ; )
        {
            cout << inputtip;
            std::string line;
            getline( cin, line );
            std::istringstream is( line );
            if( (is>>value) && (is>>std::ws).eof() )
                break;
            if( is.eof() )
                continue;
            cout << "Invalid input. Please try again.\n";
        }
        return value;
    }
};


int main( void )
{
    AccountManage mng( "accounts.txt", "transactions.txt" );

    // 输出菜单
    cout << "Menu:\n"
         << "  1. Create new account.\n"
         << "  2. Close account.\n"
         << "  3. Report lost.\n"
         << "  4. Deposit.\n"
         << "  5. Withdraw.\n"
         << "  6. Query balance.\n"
         << "  7. Transaction history.\n"
         << "  8. Exit.\n";

    for( ; ; )
    {
        int choice = inputline("Please enter your choice: " );
        if( choice == 8 ) // 退出程序
        {
            cout << "Goodbye.\n";
            break;
        }

        switch( choice )
        {
        case 1: // 开户
            {
                AccountInfo info;
                info.name = inputline("  Please enter your name: ");
                if( mng.at(info.name) )
                    cout << "  开户失败(用户名已存在).\n";
                else
                {
                    info.password = inputline("  Please enter your password: ");
                    info.phone = inputline("  Please enter your phone: ");
                    info.balance = inputline("  Please enter the initial deposit amount: ");
                    info.isLost = false;
                    if( !mng.开户(info) )
                        cout << "  开户失败(用户名已存在).\n";
                }
            }
            break;
        case 2: // 销户
            {
                std::string name = inputline("  Please enter your name: ");
                if( !mng.销户(name) )
                    cout << "  销户失败(用户名不存在).\n";
            }
            break;
        case 3: // 挂失
            {
                std::string name = inputline("  Please enter your name: ");
                if( !mng.挂失(name) )
                    cout << "  挂失失败(用户名不存在 或 已挂失).\n";
            }
            break;
        case 4: // 存款
            {
                std::string name = inputline("  Please enter your name: ");
                if( !mng.at(name) )
                    cout << "  存款失败(用户名不存在 或 已挂失).\n";
                else
                {
                    double amount = inputline("  Please enter the deposit amount: ");
                    if( !mng.存款(name,amount) )
                        cout << "  存款失败(数值错误).\n";
                }
            }
            break;
        case 5: // 取款
            {
                std::string name = inputline("  Please enter your name: ");
                if( !mng.at(name) )
                    cout << "  取款失败(用户名不存在 或 已挂失).\n";
                else
                {
                    double amount = inputline("  Please enter the withdraw amount: ");
                    double fee = inputline("  Please enter the fee amount: ");
                    if( !mng.取款(name,amount,fee) )
                        cout << "  取款失败(数值错误).\n";
                }
            }
            break;
        case 6: // 查询余额
            {
                std::string name = inputline("  Please enter your name: ");
                if( !mng.at(name) )
                    cout << "  查询余额失败(用户名不存在 或 已挂失).\n";
                else
                    cout << "  Your balance is: " << mng.查询余额(name).value() << endl;
            }
            break;
        case 7: // 查询历史交易记录
            {
                std::string name = inputline("  Please enter your name: ");
                if( !mng.at(name) )
                    cout << "  查询历史交易记录(用户名不存在 或 已挂失).\n";
                else
                    cout << "  Transaction history:\n" << mng.查询历史交易记录(name,"  ").value();
            }
            break;
        default:
            cout << "  Invalid input. Please try again.\n";
            break;
        }
    }

    return 0;
}


[此贴子已经被作者于2023-6-4 18:50编辑过]

2023-06-04 18:47
快速回复:有人能看看我这个代码为什么内存不足吗
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.023143 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved