读取ASCII文件到C++ std::string的最简单方法是什么?
- 论坛
- 读取ASCII文件到C++ std::string的最简单方法是什么?
17 浏览
匿名的
0 Comments
问题的出现原因:在C++中读取ASCII文件到std::string的最简单方法是什么?
解决方法:使用以下代码可以实现:
#include#include #include std::string readfiletostring(const std::string& filename) { std::ifstream ifs(filename); std::stringstream buffer; buffer << ifs.rdbuf(); return buffer.str(); } int main() { std::cout << readfiletostring("test.txt") << std::endl; return 0; }
可以将读取文件的代码放入一个名为`readfiletostring`的函数中,以实现通用的解决方案。然后,可以使用`std::cout << readfiletostring("test.txt") << std::endl;`的方式在`main`函数中展示其用法,如果需要的话。