如何高效地将 ifstream 读入字符串?

4

新手问题!我该如何将整个 ifstream 读入 stdlib 的字符串中?目前我正在为所有项目使用的方法浪费了很多时间:

string code;
ifstream input("~/myfile");
char c1=input.get();
while (c1!=EOF)
{
    code+=c1;
    len++;
    c1=input.get();
}

顺便说一下,我更喜欢自己处理行和空格。


1
请参见:https://dev59.com/w3A75IYBdhLWcg3wboYz#3304059 - Jerry Coffin
2个回答

8
string load_file(const string& filename)
{
    ifstream infile(filename.c_str(), ios::binary);
    istreambuf_iterator<char> begin(infile), end;
    return string(begin, end);
}

使用迭代器更加标准,我会进行基准测试以确定哪种方法更快。 - Hossein

4
#include <string>
#include <iostream>

int main() {
   std::string s;

   std::getline(std::cin, s, '\0');
   std::cout << s;
}

~


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接