我在编码和概念化此项目时遇到了问题。我已经四处寻找这个问题的答案,但几乎没有运气,也许这真的很明显。我应该提示用户一个文件名,文件是假定有以下格式:从文件中读取特定单词并将它们存储在对象中
动物:
名称:[值]
噪声:[值]
腿:[值]
(不带空格之间)
它应该能够尽量多看“动物对象”,因为该文件中,并将其储存在具有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;
}
在这种情况下重新发明车轮是否真的明智?考虑使用现有的XML库,JSON,YAML或其他任何库 – alexeykuzmin0