如何创建名称作为文本文件第一行的结构?
How do I create a struct with the name as the first line of a text file?
假设我有一个文本文件"data.txt",我创建了一个结构:
struct newperson {
string hair_colour;
int age;
}
"data.txt"包含以下信息:
Sandy
brown
23
如何创建一个 Newperson 结构并将其名称设置为"Sandy",以便它与编写相同:
newperson Sandy;
它可能会使用 getline 函数,但我不知道如何实现它......在我缺乏经验的编码头脑中,我会想象它会像
ifstream file;
string line;
getline(file, line);
Newperson line;
显然,这写得真的很糟糕,这样写可能有一百万个错误。
如果不深入研究在法律C++范围之外运行的非常奇怪的巫毒教,你就无法在运行时创建变量。不值得这样做。即使可以,变量名称也是编译时的早期牺牲品。该变量file
不再称为 file。当编译器和链接器完成它时,它可能类似于stackpointer + 32。因此,在运行时动态加载变量名称的想法是行不通的。
但是你可以创建一个变量,将一个人的名字映射到你的结构的实例。C++标准库包含几个这样的映射类,例如std::map
.
将std::map
用于案例的示例如下所示:
std::ifstream file;
std::map<std::string, newperson> people;
std::string name;
std::string hair_colour;
int age;
if (getline(file, name) &&
getline(file, haircolor) &&
file >> age)// note: I left a boobytrap here
{ // only add the person if we got a name, a hair colour and an age
people[name].hair_colour = hair_colour; // creates a newperson for name and sets
// the hair_colour
people[name].age= age; // looks up name, finds the newperson and sets their age.
// warning: This can be a little slow. Easy, but slow.
}
关于诱杀装置的提示:为什么 std::getline() 在格式化提取后跳过输入?
后来当你想查桑迪的年龄时,
people["Sandy"].age
是你所需要的一切。但请注意,如果桑迪不在people
地图中,地图将为桑迪创建并默认构造一个新条目。如果您不确定 Sandy 是否在地图中,请改用find
方法。
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 用c++从输入文件中读取另一行
- 孤立代码块在结构中引发异常
- 读取文件的最后一行并输入到链接列表时出错
- 有什么方法可以遍历结构吗
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 无法将结构注册为增强几何体3D点
- 多成员Constexpr结构初始化
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 如何重构类层次结构以避免菱形问题
- 如何在C++中序列化结构数据
- std::vector的包装器,使数组的结构看起来像结构的数组
- 在一行中使用带有"temp"结构的矢量回推(如果可能)
- "Multiple definition of.." "First defined here"数据结构中的同一行中