是否有一种方法可以从文本文件中读取并将单个数据存储为不同的变量
is there a way to read from a text file and store individual data as different variables?
我正在研究此程序:
创建一个将模拟ATM机的程序。您必须创建一个名为" ATM"的类,该类将具有成员功能:
在屏幕上创建一个问候,
向用户询问四位数别针
a(名为" PIN"的外部文件必须包含以下四个引脚和所有者名称和余额:
拉里1234 $ 200
MoE 5678 $ 350
露西0007 $ 600
雪莉9876 $ 535
b(用户的引脚输入必须匹配一个存储的引脚以允许访问交易。
c(经过3次失败的尝试,告诉用户他们的帐户被冻结,他们必须联系客户服务。
成功输入PIN后,使用其名称向用户致意。
创建一个屏幕,询问用户是否要提取或存钱或查看其余额。
初始化$ 500的开始机器余额。根据存款和撤回来跟踪余额。
不允许用户提取比当前在机器中的更多资金。
将撤回的钱限制为$ 400。
该程序必须在连续循环上运行。
我无法弄清楚如何做2b和3。我认为我应该为4个不同的人创建4个不同的对象,每个对象1行,然后在对象中分开名称,销钉和平衡,但是我'm不太确定该怎么做。
我认为我应该在循环中使用诸如getline()
之类的东西将线分开为4个对象,然后使用fin >> name >> pin >> balance;
来区分name
,pin
和balance
,但我无法弄清楚。
如果我做错了这一切,那么我真的很喜欢朝着正确的方向推动。
如果您是从输入流阅读的,则可以这样做:
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
}
- QT QOpenGLWidget:如何在不使用数据块复制的情况下修改VBO中的单个顶点值?
- 与多个 for 循环与单个 for 循环 wrt 相关的性能从多映射获取数据
- 如何使用C++中可以具有多种数据类型的单个变量
- 用于对项目进行分组并将单个项目映射到其他组成员的数据结构
- 对于单个数据 WORD 的 memcpy 和赋值语句有什么区别?
- C++ - 使用结构数据类型将单词中的单个小写字符更改为大写,反之亦然
- 是否值得使用位移在单个字节中存储多个小数据成员?
- 如何在 C++ 中使用删除运算符删除单个数据
- 结构内具有更多数据类型的单个链表
- 字符串中单个字符作为数组的数据类型是什么
- 多个快速读取器 单个慢速写入器:使用具有原子索引的阴影数据安全吗?
- 写入单个大数据文件或多个小文件:哪个更快?
- 模板参数在具有相同数据类型的单个类型名的构造函数中不起作用
- CPP中的单个参考代表两种或多个数据类型
- 是否有一种方法可以从文本文件中读取并将单个数据存储为不同的变量
- WSASend是否将所有WSABUF缓冲区作为单个数据包发送
- 多播大数据包包含多个客户端的所有信息,而单个数据包则包含目标客户端的信息
- 在多个容器中包含单个数据
- 数组和单个数据点使用指针之间的区别
- 使用加载和保存方法对不同命名空间中的单个数据类型进行提升