noob问题!我如何将'整个ifstream'读入stdlib'字符串'?我使用我的所有项目,现在目前的方式浪费了太多的时间,我认为:将ifstream读入字符串的最有效方法是什么?
string code;
ifstream input("~/myfile");
char c1=input.get();
while (c1!=EOF)
{
code+=c1;
len++;
c1=input.get();
}
BTW我喜欢做线和空白管理自己。
noob问题!我如何将'整个ifstream'读入stdlib'字符串'?我使用我的所有项目,现在目前的方式浪费了太多的时间,我认为:将ifstream读入字符串的最有效方法是什么?
string code;
ifstream input("~/myfile");
char c1=input.get();
while (c1!=EOF)
{
code+=c1;
len++;
c1=input.get();
}
BTW我喜欢做线和空白管理自己。
string load_file(const string& filename)
{
ifstream infile(filename.c_str(), ios::binary);
istreambuf_iterator<char> begin(infile), end;
return string(begin, end);
}
这使用迭代器是我认为更标准。我会做基准测试,看看哪种方式更快。 – Hossein 2011-03-17 15:35:08
#include <string>
#include <iostream>
int main() {
std::string s;
std::getline(std::cin, s, '\0');
std::cout << s;
}
〜
参见:http://stackoverflow.com/questions/3303527/how-to-pre-allocate-memory-for-a-stdstring-object/3304059#3304059 – 2011-03-17 15:54:59