使用getline()从文本文件中读取行,并将push_back读入对象向量 [英] Using getline() to read in lines from a text file and push_back into a vector of objects

查看:127
本文介绍了使用getline()从文本文件中读取行,并将push_back读入对象向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在解决类和对象的问题时,我遇到了如何正确使用 getline()的问题。我需要读取 string 类型的行,然后使用 myVec 向量中> push_back 。这是我目前的状态:

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

假定类 myClass 已实施。

感谢您的帮助。

推荐答案


假设类 myClass 已经实现。

帮助,我们不能仅仅假设它已经实现并且知道它的接口是什么或如何使用它,所以我们不能回答您的问题。

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.

您为什么期望 std :: ifstream 知道如何使用 myClass ?为什么要传递 inputFile 作为 inputFile 成员函数的参数?您是否看过任何显示如何使用 getline 的文档或示例?

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?

假设您可以构建<$ c从 std :: string 中的$ c> myClass 可以正常工作(注意它会读入 string ,请注意您不需要手动关闭文件):

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

这篇关于使用getline()从文本文件中读取行,并将push_back读入对象向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆