0

I'd like to assign std::string *ptr via std::string::operator >> in c++.

I have a class below.

class A{
public:
    A(){
        ptr = new std::string();
    }
    A(std::string& file){
        ptr = new std::string();
        std::ifstream ifs(file);
        std::stringstream ss;
        ss << ifs.rdbuf();
        *ptr=ss.str();
        ifs.close();
    }

    ~A(){
        delete ptr;
    }

    void output(std::ostream& stream) const{
        stream << *ptr;
    }

    void input(std::istream& stream) const{
        stream >> *ptr;
    }

private:
    std::string *ptr;
};

int main(void){
    std::string file="./file";
    std::string dfile="./dump";
    std::ofstream ofs(file);
    A a(file);
    a.output(ofs);

    std::ifstream ifs(dfile);
    A b();
    b.input(ifs);
    return 0;
}

Assume "./file" contains a text below:

The first form (1) returns a string object with a copy of the current contents of the stream.
The second form (2) sets str as the contents of the stream, discarding any previous contents.

I confirmed the content of "./dump" is same as "./file". However, the string object I get(b's *ptr) from b.input("./dump") is just a small string delimitered at space, which is just

The

How can I obtain whole text? Thanks

mallea
  • 485
  • 5
  • 16

1 Answers1

1

stream >> *ptr; reads a single whitespace-delimited word.

To read a whole line, use std::getline:

std::getline(stream, *ptr);

Also note that there's no point in allocating your string dynamically (in fact, in its current state your class will leak memory and cause double-deletes if copied, as pointed out by @aschepler in the comments). The member could be a plain std::string str;.

emlai
  • 37,861
  • 9
  • 87
  • 140
  • Should I repeat getline()? – mallea Feb 17 '17 at 13:28
  • If you want to read multiple lines, yes. If you want to read the whole file into the string, check the following Q&A: http://stackoverflow.com/q/2602013/3425536 – emlai Feb 17 '17 at 13:30