假设我有一个文本文件“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
不再称为文件。当编译器和链接器完成它时,它可能类似于 stackpointer + 32。因此,在运行时动态加载变量名的想法是行不通的。
但是您可以创建一个变量,将人名映射到您的结构实例。 C++ 标准库包含几个这样的映射类,for example, 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.
}
关于陷阱的提示:Why does std::getline() skip input after a formatted extraction?
稍后当你想查询 Sandy 的年龄时,
people["Sandy"].age
就是你所需要的。但请注意,如果 Sandy 不在 people
map 中, map 将为 Sandy 创建并默认构建一个新条目。如果您不确定桑迪在 map 中,use the find
method instead .
关于c++ - 如何创建一个名称作为文本文件第一行的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49330626/