ostream_iterator到一个字符串而不是cout?

时间:2014-02-09 23:38:11

标签: c++ boost copy cout

有人帮我从使用

提升的目录中获取文件名
    if (exists(p))    // does p actually exist?
    {

        if (is_directory(p))      // is p a directory?
        {
            copy(directory_iterator(p), directory_iterator(), // directory_iterator::value_type
                ostream_iterator<directory_entry>(cout, "\n")); // is directory_entry, which is

        }
    }

但我希望它在一个字符串而不是cout

我该如何捕获该副本?

1 个答案:

答案 0 :(得分:4)

您可以将内容复制到std::ostringstream并使用str()检索缓冲区的副本:

std::ostringstream buf;

std::copy(directory_iterator(p), directory_iterator(),
          std::ostream_iterator<directory_entry>(buf, "\n"));

std::string content(buf.str());