【问题标题】:What's the most efficient way of reading an ifstream into an string?将 ifstream 读入字符串的最有效方法是什么?
【发布时间】:2011-03-17 15:10:30
【问题描述】:

菜鸟问题!如何将“整个 ifstream”读入标准库“字符串”?我认为我现在用于所有项目的当前方式浪费了很多时间:

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

顺便说一句,我更喜欢自己进行行和空白管理。

【问题讨论】:

标签: c++ std


【解决方案1】:
string load_file(const string& filename)
{
    ifstream infile(filename.c_str(), ios::binary);
    istreambuf_iterator<char> begin(infile), end;
    return string(begin, end);
}

【讨论】:

  • 我认为这种使用迭代器更标准。不过,我会进行基准测试,看看哪种方式更快。
【解决方案2】:
#include <string>
#include <iostream>

int main() {
   std::string s;

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

~

【讨论】:

    猜你喜欢
    • 2020-10-24
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 2011-03-25
    相关资源
    最近更新 更多