2016-04-26 93 views
1

很多時候需要將整個文件內容讀入std :: string。 這是最簡單的方法嗎?將ASCII文件讀入C++ std :: string的最簡單方法是什麼?

+2

的[閱讀整ASCII文件到C++的std :: string]可能的複製(http://stackoverflow.com/questions/2602013/讀全的ASCII文件到-C-stdstring)。另請參見:[在C++中將文件內容讀入字符串](http://stackoverflow.com/questions/2912520/read-file-contents-into-a-string-in-c)或[什麼是最好的方法在C++中將文件轉換成std :: string?](http://stackoverflow.com/questions/116038/what-is-the-best-way-to-slurp-a-file-into-a-stdstring -in-c) –

回答

2

我們假設我們有一個文件「test.txt」。一般情況下,最好的辦法,我覺得這樣做是使用下面的代碼:

#include <iostream> 
#include <sstream> 
#include <fstream> 

int main() 
{ 
    std::ifstream ifs("test.txt"); 
    std::stringstream buffer; 
    buffer << ifs.rdbuf(); 

    std::cout << buffer.str() << std::endl; 

    return 0; 
} 
+0

推薦:將閱讀代碼放入'std :: string readfiletostring(const std :: string&filename)'或類似的函數來推廣解決方案,而不是將閱讀代碼編入'main'。然後你可以用'std :: cout << readfiletostring(「test.txt」)<< std :: endl;''main'組成的'main'演示它的用法。 – user4581301