zoukankan      html  css  js  c++  java
  • c++ istream转换为std::string

    std::istreambuf_iterator<char> eos;
    std::string s(std::istreambuf_iterator<char>(stream), eos);
    ----------------------------------------------------------------------------

    (could be a one-liner if not for MVP)

    post-2011 edit, this approach is now spelled

    std::string s(std::istreambuf_iterator<char>(stream), {});
    ----------------------------------------------------------------------------

    I'm late to the party, but here is a fairly efficient solution:

    std::string gulp(std::istream &in)
    {
        std::string ret;
        char buffer[4096];
        while (in.read(buffer, sizeof(buffer)))
            ret.append(buffer, sizeof(buffer));
        ret.append(buffer, in.gcount());
        return ret;
    }

    I did some benchmarking, and it turns out that the std::istreambuf_iterator technique (used by the accepted answer) is actually much slower. On gcc 4.4.5 with -O3, it's about a 4.5x difference on my machine, and the gap becomes wider with lower optimization settings.

    ----------------------------------------------------------------------------

    You can try using something from algorithms. I have to get ready for work but here's a very quick stab at things (there's got to be a better way):

    copy( istreambuf_iterator<char>(stream), istreambuf_iterator<char>(), back_inserter(s) );
    ----------------------------------------------------------------------------

    You could do

    std::string s;
    std::ostringstream os;
    os<<stream.rdbuf();
    s=os.str();

    but I don't know if it's more efficient.

    Alternative version:

    std::string s;
    std::ostringstream os;
    stream>>os.rdbuf();
    s=os.str();
    ----------------------------------------------------------------------------

    Well, if you are looking for a simple and 'readable' way to do it. I would recomend add/use some high level framework on your project. For that I's always use Poco and Boost on all my projects. In this case, with Poco:

        string text;
        FileStream fstream(TEXT_FILE_PATH);
        StreamCopier::copyToString(fstream, text);
    ----------------------------------------------------------------------------

    Perhaps this 1 line C++11 solution:

    std::vector<char> s{std::istreambuf_iterator<char>{in},{}};
     
     
  • 相关阅读:
    关于SQL的一些小知识
    关于VO中的Attribute的问题
    关于JDEV的连接问题
    object xml
    自己写的一个用于往文件中插入字符串及空格的bat
    修改 SQL SERVER 2008 編輯前200筆 資料表問題? 转载自:http://www.dotblogs.com.tw/easy1201/archive/2008/12/04/6179.aspx
    Create Advanced Web Applications With Object-Oriented Techniques
    需求第一
    fwrite() and UTF8 转载
    mysql 表字段与关键字相同的话
  • 原文地址:https://www.cnblogs.com/yuanxiaoping_21cn_com/p/6720155.html
Copyright © 2011-2022 走看看