英文:
Print new line in xml file when \n literally prints \n
问题
我正在尝试在Golang中编写一个.xml文件,当我尝试写入一个新行并使用\n时,它会将\n作为字符串的一部分直接打印出来。
我该如何强制在文件中打印一个新行?
以下是我目前的代码:
fmt.Fprint(file, "<card>\n")
fmt.Fprintf(file, `<title>title</title>\n`)
但实际打印出来的是<card>\n<title>title</title>\n
。
英文:
I'm trying to write a .xml file in golang and when I try to write to a newline and use \n, it literally prints \n as part of the string.
How can I force a new line to be printed in the file?
Here is what my code looks like so far:
fmt.Fprint(file, "<card>\n")
fmt.Fprintf(file, `<title>title</title>\n`)
and that is printing <card>\n<title>title</title>\n
答案1
得分: 2
实际上,它正在打印
<card>
<title>title</title>\n
你可以在这里看到。
原因是反斜杠在原始字符串中不会被插值,即用`括起来的字符串。如果你将第二行替换为
fmt.Fprintf("<title>title</title>\n")
你的程序应该按预期工作。
英文:
Actually, it's printing
<card>
<title>title</title>\n
As you can see here.
The reason is that backslashes are not interpolated in raw strings, i.e. strings that are enclosed with `. If you replace your second line with
fmt.Fprintf("<title>title</title>\n")
your program should work as intended.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论