2017-02-17 68 views
0

我想通過std :: string :: operator >>在C++中分配std :: string * ptr。在C++中通過std :: istream分配字符串對象

我下面有一堂課。

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

假設 「./file」 包含以下內容:

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. 

我證實的 「./dump」 的內容是一樣的 「./file」。 但是,字符串對象,我從b.input得到(B的* PTR)(「./轉儲」)只是一小串delimitered的空間,這就是

The 

我怎樣才能獲得整個文本? 謝謝

+1

危險! 'A'違反了三條規則。 – aschepler

回答

1

stream >> *ptr;讀取單個以空格分隔的單詞。

要閱讀一整行,使用std::getline

std::getline(stream, *ptr); 

另外請注意,有沒有點在動態分配的字符串(事實上,在當前狀態下你的類將導致內存泄漏,並造成雙-deletes如果被複制,正如@aschepler在註釋中指出的那樣)。該成員可能是一個普通的std::string str;

+0

我應該重複getline()嗎? – mallea

+0

如果你想閱讀多行,是的。如果要將整個文件讀入字符串,請檢查以下問答:http://stackoverflow.com/q/2602013/3425536 – emlai