2015-04-19 97 views
-3

如何將istream轉換爲字符串,當我的istream還包含換行符時,我不想轉義空格? 謝謝。Istream在C++中使用 n字符進行字符串轉換

+0

您的意思是您希望字符串包含文字字符''''和''n''而不是換行符? –

+0

即使只是詢問將一個流「轉換」爲一個字符串,也意味着一個根本性的誤解。流是數據流,而字符串是字節的容器。這兩者完全不同。你的意思是你希望從流中提取所有字節到一個字符串,直到流乾燥(達到EOF)?或者是什麼?具體而準確。 –

+0

未格式化的輸入功能? 'noskipws'?用'istreambuf_iterator 's初始化它? – chris

回答

0

如果您的意思是如何將整個std::istream複製到std::string那麼有很多方法。

這裏是一個:

int main() 
{ 
    // here is your istream 
    std::ifstream ifs("test.txt"); 

    // copy it to your string 
    std::string s; 
    for(char c; ifs.get(c); s += c) {} 

    // display 
    std::cout << s << '\n'; 
} 
0

你可以只分配一個字符串足夠大,你的整個文件,並在一次閱讀:

ifstream fd(filename);   // open your stream (here a file stream) 
if (!fd) 
    exit(1); 

fd.seekg(0, ios_base::end);  // go to end of file 
size_t filesize = fd.tellg(); // dtermine size to allocate 
fd.seekg(0, ios_base::beg);  // go to the begin of your file 

string s;      // create a new string 
s.resize(filesize+1);   // reserve enough space to read 

fd.read(&s[0], filesize);  // read all the file at one 
size_t bytes_read = fd.gcount(); // it could be than less bytes are read 
s.resize(bytes_read);   // adapt size 
1

可以使用istreambuf_iterator

#include <iostream> 
#include <string> 
#include <fstream> 

int main() 
{ 
    std::ifstream ifile("test.txt"); // open 
    std::string str(std::istreambuf_iterator<char>(ifile), {}); // initialize 
    std::cout << str; // display 
}