我想std::string
用c ++ 读取文本文件的全部内容到一个对象.
使用Python,我可以写:
text = open("text.txt", "rt").read()
它非常简单而优雅.我讨厌丑陋的东西,所以我想知道 - 用C++读取文本文件最优雅的方法是什么?谢谢.
有很多方法,你选择哪种方式最适合你.
读入char*:
ifstream file ("file.txt", ios::in|ios::binary|ios::ate); if (file.is_open()) { file.seekg(0, ios::end); size = file.tellg(); char *contents = new char [size]; file.seekg (0, ios::beg); file.read (contents, size); file.close(); //... do something with it delete [] contents; }
进入std :: string:
std::ifstream in("file.txt"); std::string contents((std::istreambuf_iterator(in)), std::istreambuf_iterator ());
进入vector
std::ifstream in("file.txt"); std::vectorcontents((std::istreambuf_iterator (in)), std::istreambuf_iterator ());
使用stringstream进入字符串:
std::ifstream in("file.txt"); std::stringstream buffer; buffer << in.rdbuf(); std::string contents(buffer.str());
file.txt只是一个例子,一切都适用于二进制文件,只需确保在ifstream构造函数中使用ios :: binary.
这个主题还有另一个主题.
我的解决方案来自这个线程(两个单行):
很好(见米兰的第二个解决方案):
string str((istreambuf_iterator(ifs)), istreambuf_iterator ());
和快:
string str(static_cast(stringstream() << ifs.rdbuf()).str());