如何创建名称作为文本文件第一行的结构?

How do I create a struct with the name as the first line of a text file?

本文关键字:一行 结构 文件 创建 何创建 文本      更新时间:2023-10-16

假设我有一个文本文件"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方法。