是否有一种方法可以从文本文件中读取并将单个数据存储为不同的变量

is there a way to read from a text file and store individual data as different variables?

本文关键字:单个 数据 读取 存储 变量 文件 一种 方法 文本 是否      更新时间:2023-10-16

我正在研究此程序:

创建一个将模拟ATM机的程序。您必须创建一个名为" ATM"的类,该类将具有成员功能:

  1. 在屏幕上创建一个问候,

  2. 向用户询问四位数别针

    a(名为" PIN"的外部文件必须包含以下四个引脚和所有者名称和余额:

    拉里1234 $ 200

    MoE 5678 $ 350

    露西0007 $ 600

    雪莉9876 $ 535

    b(用户的引脚输入必须匹配一个存储的引脚以允许访问交易。

    c(经过3次失败的尝试,告诉用户他们的帐户被冻结,他们必须联系客户服务。

  3. 成功输入PIN后,使用其名称向用户致意。

  4. 创建一个屏幕,询问用户是否要提取或存钱或查看其余额。

  5. 初始化$ 500的开始机器余额。根据存款和撤回来跟踪余额。

  6. 不允许用户提取比当前在机器中的更多资金。

  7. 将撤回的钱限制为$ 400。

  8. 该程序必须在连续循环上运行。

我无法弄清楚如何做2b和3。我认为我应该为4个不同的人创建4个不同的对象,每个对象1行,然后在对象中分开名称,销钉和平衡,但是我'm不太确定该怎么做。

我认为我应该在循环中使用诸如getline()之类的东西将线分开为4个对象,然后使用fin >> name >> pin >> balance;来区分namepinbalance,但我无法弄清楚。

如果我做错了这一切,那么我真的很喜欢朝着正确的方向推动。

如果您是从输入流阅读的,则可以这样做:

struct User {
    std::string name;
    int pin;
    int amnt;
};
User read_user(std::istream& stream) {
    User user;
    // Reads in the username (this assumes the username doesn't contain a space)
    stream >> user.name; 
    // Reads in the pin as an integer
    stream >> user.pin;
    stream.ignore(2); //Ignore the extra space and dollar sign
    // Reads in the dollar amount as an integer
    stream >> user.amnt; 
    // Returns the user
    return user;
}

这将允许您从std::cin或FileStream读取,并将以名称,PIN和金额返回用户。

我们可以在这样的多个用户中阅读。基本上,我们只多次致电read

std::vector<User> read_users(std::istream& stream, int n) {
    std::vector<User> users; 
    for(int i = 0; i < n; i++) {
        users.push_back(read_user(stream)); 
    }
    return users; 
}

这将以您想要的方式阅读尽可能多的用户。

在文件中阅读所有用户

我们还可以在文件中的所有用户中阅读。

std::vector<User> read_all_users(std::istream& stream) {
    std::vector<User> users; 
    while(true) // Checks that there's stuff left in the stream
    {
        User u = read_user(stream); // Try reading a user
        if(not stream) break; // If there was nothing left to read, exit
        users.push_back(u); 
    }
    return users; 
}

示例用法:

我们将打开一个名为users.txt的文件,然后读取所有文件。然后,我们将打印每个用户的名称,PIN和帐户余额。

int main() {
    std::ifstream user_file("users.txt"); 
    std::vector<User> users = read_all_users(user_file); 
    // This prints out the name, pin, and balance of each user
    for(User& user : users) {
        std::cout << "Name: " << user.name << 'n';
        std::cout << "Pin: " << user.pin << 'n';
        std::cout << "Amnt: " << user.amnt << 'n';
    }
    // Do stuff with the list of users
}