【问题标题】:Cpp create string creation without initialization [duplicate]Cpp在没有初始化的情况下创建字符串[重复]
【发布时间】:2022-01-11 03:31:49
【问题描述】:

我想将文件的内容读入字符串。

string contents(size, '\0'); -> size was determined above using the file.seekg and file.tellg.
file.read((char*) contents.data(), size);

现在,我知道file.read中字符串的内容会被覆盖,所以不需要将字符串初始化为空字符。

有办法吗?

【问题讨论】:

    标签: c++ string filestream


    【解决方案1】:

    你可以这样做:

    std::string contents(std::istreambuf_iterator<char>{file},
        std::istreambuf_iterator<char>{});
    

    但它可能不会更快。无论哪种方式,与从驱动器读取相比,初始化都可能非常快。

    【讨论】:

    • "它可能不会更快。"为什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    • 2022-10-08
    • 2021-11-29
    相关资源
    最近更新 更多