【问题标题】:stream to write to a file as well as write to a string variable流写入文件以及写入字符串变量
【发布时间】:2020-03-30 12:44:14
【问题描述】:

我正在尝试在函数中将数据放入文件的场景。

func(std::ofstream fileStream, JsonData)
{
parses the Json and does some logic and puts to fil stream
}
std::ofstream fileStream(filename);
func(fileStream, jsonData);
//want a scenario where std::string aa will get values in ofstream.
fileStream.close();

如果我可以将流数据转换为 std::string,谁能帮助我? 我看到ostream可以转换为stringstream;并且可以移至 std::string ;但无法使用 ostream 打开文件。

请帮帮我...

【问题讨论】:

  • 您是否有理由不能将所有内容通过管道传输到字符串流中,获取字符串,然后将该字符串写入文件?
  • 请贴出真实代码。 func(std::ofstream fileStream, JsonData) 尝试按值传递 ofstream,这是不可能的。

标签: c++ file-handling stringstream ofstream ostream


【解决方案1】:

改变

func(std::ofstream fileStream, JsonData)
{
parses the Json and does some logic and puts to fil stream
}

成为

func(std::ostream& Stream, JsonData)
{
    //parses the Json and does some logic and puts to fill Stream
}

现在您可以做的是将stringstream 传递给函数并填充它。然后你可以从中得到一个字符串,并将它的缓冲区传递给一个 ofstream 之类的

JsonData data;
std::stringstream ss;
// populate string stream
func(ss, data); 
// get string
std::string stringifiedData = ss.str();
// open file
std::ofstream fileStream(filename);
// write to file
fileStream << ss.rdbuf();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-16
    • 2011-10-24
    • 1970-01-01
    • 2023-03-29
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多