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

时间:2018-03-16 23:03:42

标签: c++ c++11 syntax getline

假设我有一个文本文件“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;

显然这写起来真的很糟糕,这样的写作可能有一百万个错误。

1 个答案:

答案 0 :(得分:1)

你无法在运行时制作变量,而无需深入研究在合法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.
}

提示boobytrap:Why does std::getline() skip input after a formatted extraction?

后来当你想要查看桑迪的年龄时,

people["Sandy"].age

就是你所需要的。但请注意,如果Sandy不在people地图中,地图将创建并默认为Sandy构建一个新条目。如果您不确定Sandy在地图中,use the find method instead