0

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.

beakr
  • 5,709
  • 11
  • 42
  • 66

1 Answers1

2

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()

digital_revenant
  • 3,274
  • 1
  • 15
  • 24
  • `f` actually represents a `std::string` that was an argument to a function with my slurp code. I still get the error with `c_str()`. – beakr Nov 02 '13 at 17:08
  • Your code compiles properly for me. Have you included all the headers? Check [here](http://ideone.com/7FQvSX) – digital_revenant Nov 02 '13 at 17:25
  • Ah, I've found it. I was passing a pointer as an argument to the slurp function. – beakr Nov 02 '13 at 17:31