【问题标题】:Converting a file content to string stream using istreambuf_iterator<>使用 istreambuf_iterator<> 将文件内容转换为字符串流
【发布时间】:2023-03-06 06:26:01
【问题描述】:

我正在使用以下代码(使用命名空间 std)将文件的内容转换为字符串。

代码 1

string fileToString(const string& filename)
{
    ifstream file(filename, ios::binary);
    if (!file) return "";
    string str(istreambuf_iterator<char>(file),
               (istreambuf_iterator<char>()));
    return str;
}

我觉得上面的代码可以正常工作很奇怪(我将 string::size() 与在 Windows 资源管理器中找到的实际文件大小相匹配),但下面的代码不能:

代码 2

string fileToString(const string& filename)
{
    ifstream file(filename, ios::binary);
    if (!file) return "";
    string str(istreambuf_iterator<char>(file),
               istreambuf_iterator<char>());
    return str;
}

注意第二个参数周围缺少括号。第二个函数给出以下编译器错误:

1 错误 C2664: 'std::basic_string<_elem>::basic_string(const std::basic_string<_elem>Ax> &)' : 无法转换参数 1 来自 'std::string (_cdecl *)(std::istreambuf_iterator<_elem>,std::istreambuf_iterator<_elem>Traits> (_cdecl *)(void))' 到 'const std::basic_string<_elem> &'

2 IntelliSense:不存在合适的构造函数来转换 “标准::字符串(标准::istreambuf_iterator> 文件,std::istreambuf_iterator> (*)())" 到“std::basic_string, std::allocator>"

我正在使用 Visual Studio 2010,Windows XP SP3 上的 Win32 控制台应用程序。

令我惊讶的是,以下代码可以按预期编译和工作:

代码 3

string fileToString(const string& filename)
{
    ifstream file(filename, ios::binary);
    if (!file) return "";
    return string(istreambuf_iterator<char>(file),
                  istreambuf_iterator<char>());
}

为什么代码2会产生编译错误?

【问题讨论】:

标签: c++ visual-c++ compiler-errors


【解决方案1】:

为什么 Code 2 会产生编译错误?

代码 2 产生编译错误,因为在代码 2 中,以下行声明了一个函数:

string str(istreambuf_iterator<char>(file),
           istreambuf_iterator<char>());

它声明了一个函数。函数名称是 str 。返回类型为string。该函数有两个参数:

  • 第一个参数的类型为istreambuf_iterator&lt;char&gt;
  • 第二个参数的类型是istreambuf_iterator&lt;char&gt; (*)(),它是函数指针类型,返回istreambuf_iterator&lt;char&gt;,不接受任何参数。

所以在代码 2 中,您返回一个名为 str 的函数。由于无法转换为string函数的返回类型fileToString,因此编译出错。

在 Code1 和 Code3 中,没有这样的问题,因此它们按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    相关资源
    最近更新 更多