0

私はいくつかのかなり単純な C++ コードを使用して、ファイルの内容を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();

しかし、コンパイルすると、次のエラーが発生します。

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>}’

これはおそらく単純な間違いであることはわかっていますが、私はまだ C++ をかなり学んでいます。単純なタイプの取り違えか何かでなければなりません。

リクエストに応じて、私がやろうとしていることのサンプルコードを次に示します。

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;
}

ありがとう。

4

1 に答える 1

2

new動的割り当てが必要でない限り、C++を使用してオブジェクトを作成しないでください。newポインターを返します。これはうまくいくはずです。

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

のコンストラクターは a をstd::ifstream期待するconst char *ので、使用する必要がありますstd::string::c_str()

于 2013-11-02T17:04:38.367 に答える