Question

I'm using some fairly simple C++ code to slurp the contents of a file into a std::string:

// Read contents of file given to a std::string.
std::string f = "main.js";
std::ifstream ifs(f.c_str());
std::stringstream sstr;
sstr << ifs.rdbuf();
std::string code = sstr.str();

But when I compile, I get this error:

error: could not convert ‘((*(const std::allocator<char>*)(& std::allocator<char>())),
(operator new(4u), (<statement>, ((std::string*)<anonymous>))))’ from ‘std::string*
{aka std::basic_string<char>*}’ to ‘std::string {aka std::basic_string<char>}’

I know this is probably a simple mistake but I'm still very much learning C++. Should just be a simple type mixup or something.

On request, here is some example code of what I'm trying to do:

std::string Slurp(std::string f)
{
    std::ifstream ifs(f.c_str());
    std::stringstream sstr;
    sstr << ifs.rdbuf();
    std::string code = sstr.str();
    return code;
}

Thanks.

Was it helpful?

Solution

You don't create objects using new in C++ unless you want dynamic allocation. new returns a pointer. This should work.

std::string f("main.js");
std::ifstream ifs(f.c_str());

The constructor of std::ifstream expects a const char * so you need to use std::string::c_str()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top