gpt4 book ai didi

c++ - 用 C++ 编写文本/二进制文件最优雅的方法是什么?

转载 作者:太空狗 更新时间:2023-10-29 20:06:58 24 4
gpt4 key购买 nike

我在阅读中发现了一些不错的结果,例如:Read txt with iterators and preallocation , 或 read into containers .所以我想知道如何将最优雅的 std::string 写入文件?

编辑:读取时我可以通过 seek 和 tellg 为字符串预分配空间,因为我知道字符串的大小,我怎么能告诉文件系统我想写多少?

最佳答案

这里有一个关于如何输出 std::string 的小例子,但你应该仔细阅读 fstream

#include <iostream>
#include <fstream>
#include <string>

int main(int argc, char *argv[])
{

std::string s("writemeout");
std::ofstream outfile("output.txt");
if(!outfile.is_open()) {
std::cerr << "Couldn't open 'output.txt'" << std::endl;
return -1;
}

outfile << s << std::endl;
outfile.close();
return 0;
}

关于c++ - 用 C++ 编写文本/二进制文件最优雅的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5257049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com