【问题标题】:Error: cannot convert in simple std::string file slurper错误:无法在简单的 std::string 文件中转换
【发布时间】:2013-11-02 17:02:05
【问题描述】:

我正在使用一些相当简单的 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;
}

谢谢。

【问题讨论】:

    标签: c++ file scripting ifstream sstream


    【解决方案1】:

    除非您想要动态分配,否则不要在 C++ 中使用 new 创建对象。 new 返回一个指针。这应该可以。

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

    std::ifstream 的构造函数需要一个const char *,所以你需要使用std::string::c_str()

    【讨论】:

    • f 实际上代表了一个 std::string,它是一个带有我的 slurp 代码的函数的参数。我仍然收到c_str() 的错误。
    • 您的代码可以为我正确编译。您是否包含所有标题?检查here
    • 啊,我找到了。我将一个指针作为参数传递给 slurp 函数。
    猜你喜欢
    • 2017-03-10
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多