从文件中读取特定单词并将它们存储在对象中
我在编码和概念化此项目时遇到了问题。我已经四处寻找这个问题的答案,但几乎没有运气,也许这真的很明显。我应该提示用户一个文件名,文件是假定有以下格式:从文件中读取特定单词并将它们存储在对象中
动物:
名称:[值]
噪声:[值]
腿:[值]
(不带空格之间)
它应该能够尽量多看“动物对象”,因为该文件中,并将其储存在具有3个参数(名称,噪音,腿)的动物对象类。
我的问题主要是在阅读文件的过程中,我无法弄清楚读取文件和存储信息的好方法。这是我现在的代码。任何帮助我现在有的代码和存储值的想法。对不起,如果我解释什么不好,请问澄清,如果我做了,谢谢你。
cout << "Enter the file name: ";
string fileName;
getline(cin, fileName);
cout << endl;
try
{
ifstream animalFile(fileName);
if (!animalFile.good()) // if it's no good, let the user know and let the loop continue to try again
{
cout << "There was a problem with the file " << fileName << endl << endl;
continue;
}
string line;
while (animalFile >> line) // To get you all the lines.
{
getline(animalFile, line); // Saves the line in STRING.
cout << line << endl; // Prints our STRING.
}
}
catch (...)
{
cout << "There was a problem with the file " << fileName << endl << endl;
}
如果你真的有这种文件格式绑定,可考虑做以下读取数据并将其存储:
#1。定义类别Animal
以表示动物:
struct Animal
{
std::string name;
int legs;
int noise;
}
#2。定义一个istream& operator >> (istream&, Animal&)
来读取这种类型的一个对象并检查输入的正确性。
std::istream& operator >> (std::istream& lhs, Animal& rhs)
{
std::string buf;
lhs >> buf >> buf >> rhs.name >> buf >> rhs.noise >> buf >> rhs.legs;
}
#3。使用std::copy
和std::istream_iterator
来读取文件中的所有值std::vector
:
std::istream_iterator<Animal> eos;
std::istream_iterator<Animal> bos(animalFile);
std::vector<Animal> zoo;
std::copy(bos, eos, std::back_inserter(zoo));
此代码对输入错误没有检查,它可以很容易地添加到istream& operator >> (istream&, Animal&)
。
谢谢你的回答。因此,为了澄清,#2只是读取文件来检查格式,没有别的?同样,对于#3,你能否给我一个解释,哪一行代码在做什么,我很难完全掌握它,甚至不知道它应该做什么。 – Roberto
@Roberto#2实际上读取数据并通过存储在输出参数'rhs'中来返回它。该操作符可以如下使用:'动物a; cin >> a;'。 – alexeykuzmin0
#3:'std :: vector'只是'Animal'的一个动态数组。 'istream_iterator
在这种情况下重新发明车轮是否真的明智?考虑使用现有的XML库,JSON,YAML或其他任何库 – alexeykuzmin0