在命令提示符下看到换行符,但在文件输出中可以看到 相同的字符串

New line seen in command prompt but the same string is seen with in file output

本文关键字:字符串 文件 命令提示符 换行符 输出      更新时间:2023-10-16

>我有这段运行良好的代码

#include <iostream>
#include <set>
#include <sstream>
int main()
{   
    std::set<std::string> a;
    a.insert("foo");
    a.insert("bar");
    a.insert("zoo");
    a.insert("should");
    a.insert("work");
    std::stringstream b;
    std::set<std::string>::iterator it;
    for (it = a.begin(); it != a.end(); it++)
    {
        b << " " << *it <<"," <<"n";
    }
    std::string aaa = b.str();
    std::cout <<aaa;
}

命令提示符下的输出:

bar, //new line after ","
foo, //new line after ","
should,
work,
zoo,
如果我尝试在文件中写入相同的字符串

aaa,我希望相同的输出在文件中打印,即换行中","之后的每个字符串,而是我在文件中获得如下输出(在单行中带有 (:

" bar,n foo,n should,n work,n zoo,n"

谁能帮我解决这个问题?

有关在文件中写入字符串的详细信息:

以下是我写入文件的方式:

boost::property_tree::ptree pt1;
pt1.put( "Output", aaa );
boost::property_tree::write_json( "result.json", pt1 );

这将写入JSON文件,上述代码在(Windows - NotePad/NotePad++(中的输出如下:

{
    "Output": " bar,n foo,n should,n work,n zoo,n"
}

你不是在写一个普通的文件!您正在使用 JSON 库为您编写文件。碰巧的是,在 JSON 字符串中,行尾字符就像在 C 源文件中一样被转义,即 "n" .

所以,总结一下,这是预期的行为。如果你想得到正常的行尾字符,写一个普通的文件,与fopen()和朋友一起。

这是

预期行为。

您将字符串(包含换行符(传递给 JSON 库以编码为 JSON。该编码步骤包括将换行符转换为子字符串"",因为这就是我们在 JSON 中表示字符串内换行符的方式。

在 json.org 网站上阅读有关 JSON 的更多信息。