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