从文件中读取特定单词并将其存储在对象中

时间:2016-08-01 07:36:59

标签: c++ class getline

我在编写和概念化这个项目时遇到了麻烦。我已经四处寻找这个问题的答案,但几乎没有运气,也许它真的很明显。我应该提示用户输入文件名,假定文件格式如下:

动物

姓名:[值]

噪音:[价值]

腿:[值]

(中间没有空格)

应该能够阅读尽可能多的动物物品"因为文件中存在并将它们存储在具有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 个答案:

答案 0 :(得分:0)

如果您真的使用此文件格式绑定,请考虑执行以下操作以读取数据并将其存储:

#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::copystd::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&)