Using getline() to read in lines from a text file and push_back into a vector of objects

StackOverflow https://stackoverflow.com/questions/22390500

Вопрос

I am having issues figuring out how to properly use getline() when it comes to classes and objects. I am needing to read in lines of string type and then add them to the myVec vector using push_back. Here is what I have at the moment:

vector<myClass> read_file(string filename)
{
    vector<myClass> myVec;
    myClass line;
    ifstream inputFile(filename);
    if (inputFile.is_open())
    {
        while (inputFile.getline(inputFile, line)) // Issue it here.
        {
            myVec.push_back(line);
        }
        inputFile.close();
    }
    else
        throw runtime_error("File Not Found!");

    return myVec;
}

Assume the class myClass is already implemented.

Thanks for the help.

Это было полезно?

Решение 2

Assume the class myClass is already implemented.

That doesn't help, we can't just assume it's implemented and know what its interface is or how to use it, so we can't answer your question.

Why do you expect std::ifstream to know how to work with myClass? Why are you passing inputFile as an argument to a member function of inputFile? Have you looked at any documentation or examples showing how to use getline?

Assuming you can construct a myClass from a std::string this will work (note it reads into a string and note you don't need to close the file manually):

vector<myClass> read_file(string filename)
{
    ifstream inputFile(filename);
    if (!inputFile.is_open())
        throw runtime_error("File Not Found!");

    vector<myClass> myVec;
    string line;
    while (getline(inputFile, line))
    {
        myClass m(line);
        myVec.push_back(m);
    }

    return myVec;
}

Другие советы

Your usage of getline doesn't match the signature - you have arguments of wrong type.

istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );

If you want to add a myClass element to the vector based on the string you read, you have to construct it first and then push it back.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top