在类中使用fstream getline()函数

Using the fstream getline() function inside a class

本文关键字:getline 函数 fstream      更新时间:2023-10-16

我正在尝试将包含字典单词的文本文件的行加载到数组对象中。我想要一个数组来容纳所有以"a"开头的单词,另一个数组代表"b"。。。对于字母表中的所有字母。

这是我为数组对象编写的类。

    #include <iostream>
    #include <string>
    #include <fstream>
    using namespace std;
    class ArrayObj
    {
    private:
        string *list;
        int size; 
    public:

        ~ArrayObj(){ delete list;}
        void loadArray(string fileName, string letter)
        {
            ifstream myFile;
            string str = "";
            myFile.open(fileName);
            size = 0;
            while(!myFile.eof())
            {
                myFile.getline(str, 100);
                if (str.at(0) == letter.at(0))
                    size++;
            }
            size -= 1; 
            list = new string[size];
            int i = 0;
            while(!myFile.eof())
            {
                myFile.getline(str, 100);
                if(str.at(0) == letter.at(0))
                {
                    list[i] = str;
                    i++;
                }
            }
            myFile.close();
        }

    };

我得到一个错误说:

2   IntelliSense: no instance of overloaded function     "std::basic_ifstream<_Elem, _Traits>::getline [with _Elem=char, _Traits=std::char_traits<char>]" matches the argument list d:champlainspring 2012algorithms and data structuresweeks 8-10map2arrayobj.h  39

我想这需要我重载getline函数,但我不太确定如何进行,也不太确定为什么有必要这样做。

有什么建议吗?

处理std::string的流函数不是istream的成员函数,而是一个自由函数。(成员函数版本处理char*)。

std::string str;
std::ifstream file("file.dat");
std::getline(file, str);

值得注意的是,有更好、更安全的方法可以这样做:

#include <fstream>
#include <string>
#include <vector>
//typedeffing is optional, I would give it a better name
//like vector_str or something more descriptive than ArrayObj
typedef std::vector<std::string> > ArrayObj
ArrayObj load_array(const std::string file_name, char letter)
{
    std::ifstream file(file_name);
    ArrayObj lines;
    std::string str;
    while(std::getline(file, str)){
        if(str.at(0)==letter){
            lines.push_back(str);
        }
    }
    return lines;
}

int main(){
    //loads lines from a file
    ArrayObj awords=load_array("file.dat", 'a');
    ArrayObj bwords=load_array("file.dat", 'b');
    //ao.at(0); //access elements
}

不要重新发明轮子;结账矢量它们是标准的,将为您节省大量时间和痛苦。

最后尽量不要放在using namespace std中,这是不好的,原因有很多,我不会深入;相反,在std对象前面加上std::,就像std::cout或std::string一样。

http://en.cppreference.com/w/cpp/container/vectorhttp://en.cppreference.com/w/cpp/string/basic_string/getlinehttp://en.cppreference.com/w/cpp/string