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

蹲街弑〆低调 提交于 2019-12-08 11:15:36

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/22390500/using-getline-to-read-in-lines-from-a-text-file-and-push-back-into-a-vector-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!