简体   繁体   中英

Reading specific words from a file and storing them in an object

I'm having trouble coding and conceptualizing this project I was assigned. I've looked around for answers to this issue but had little to no luck, maybe it's really obvious. I'm supposed to prompt the user to a filename, the file is assume to have the following format:

Animal:

Name: [value]

Noise: [value]

Legs: [value]

(with no spaces in between)

It should be able to read as many "animal objects" as there are in the file and store them in an animal object class that has 3 parameters (name, noise, legs).

My issue is mostly during the reading in of the file, I can't figure out a good method for reading the file AND storing the information. Here is the code I currently have. Any help with the code I currently have and ideas for storing the values. Sorry if I explained anything poorly, please ask to clarify if I did, thank you in advance.

    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;
    }

If you're really binded with this file format, consider doing the following to read the data and store it:

#1. Define a class Animal to represent an animal:

struct Animal
{
    std::string name;
    int legs;
    int noise;
}

#2. Define an istream& operator >> (istream&, Animal&) to read one object of this type and check for the correctness of the input.

std::istream& operator >> (std::istream& lhs, Animal& rhs)
{
    std::string buf;
    lhs >> buf >> buf >> rhs.name >> buf >> rhs.noise >> buf >> rhs.legs;
}

#3. Use std::copy and std::istream_iterator to read all the values from the file to 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));

This code has no checking for input errors, which may easily be added into istream& operator >> (istream&, Animal&) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM