Using the fstream getline() function inside a class

the function for streams that deals with std::string is not a member function of istream but rather a free function it is used like so. (the member function version deals with char*).

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

It is worth noting there are better safer ways to do what you are trying to do like so:

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

don’t reinvent the wheel; checkout vectors they are standard and will save you a lot of time and pain.

Final try not to put in using namespace std that is bad for a whole host of reasons I wont go into; instead prefix std objects with std:: so like std::cout or std::string.

http://en.cppreference.com/w/cpp/container/vector http://en.cppreference.com/w/cpp/string/basic_string/getline http://en.cppreference.com/w/cpp/string

Leave a Comment