2

Why does this code give an error trying to convert from a string constructed from std::istreambuf_iterator<char>'s to a regular default constructed string?

#include <string>
#include <streambuf>

int main()
{
    std::string filePath = "path";
    std::string source( 
        std::istreambuf_iterator<char>( 
            std::ifstream( filePath ) ),
            std::istreambuf_iterator<char>() );

    std::string s2 = source;
}

http://cpp.sh/6ptt5

Edit: Added error message.

11:26: error: conversion from 'std::string(std::istreambuf_iterator<char,
 std::char_traits<char> > (*)(std::ifstream), std::istreambuf_iterator<char, 
std::char_traits<char> > (*)()) {aka std::basic_string<char>
(std::istreambuf_iterator<char, std::char_traits<char> > 
(*)(std::basic_ifstream<char>), std::istreambuf_iterator<char, 
std::char_traits<char> > (*)())}' to non-scalar type 'std::string {aka 
std::basic_string<char>}' requested
  • 1
    That's *most vexing parse* right there. – HolyBlackCat May 20 '19 at 22:54
  • 1
    There are two problems here: 1) [Most vexing parse](https://stackoverflow.com/questions/7007817/a-confusing-detail-about-the-most-vexing-parse) and 2) `istreambuf_iterator` takes an lvalue as its first argument, but you are attempting to bind it to an rvalue (`ifstream( filePath )`). A simple fix to the most vexing parse issue is to do `std::ifstream( filePath ) >> std::skipws`. Calling the `skipws` manipulator is basically a no-op. This will also fix your second issue because the result of that expression will be an lvalue. – David G May 20 '19 at 22:58

0 Answers0