C++新行不翻译
首先,我是 C++ 的初学者。
我正在使用 API 进行编码,并且希望将包含新行的文本传递给它,并让它在另一端打印出新行。
如果我对我想要打印的内容进行硬编码,就像这样,
printInApp("Hello\nWorld");
它确实在另一端以单独的行形式出现,但是如果我使用返回 const char 的方法从应用程序中检索文本,那么将其直接传递给 printInApp (它以 const char 作为参数),它以单行形式出现。
这是为什么?我该如何解决它?
First off, I'm a complete beginner at C++.
I'm coding something using an API, and would like to pass text containing new lines to it, and have it print out the new lines at the other end.
If I hardcode whatever I want it to print out, like so
printInApp("Hello\nWorld");
it does come out as separate lines in the other end, but if I retrieve the text from the app using a method that returns a const char then pass it straight to printInApp (which takes const char as argument), it comes out as a single line.
Why's this and how would I go about to fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
处理字符串文字中的转义码的是编译器,而不是运行时方法。这就是为什么你可以使用“char c = '\n';”因为编译器只是将其编译为“char c = 10”。
如果您想将“\”和“n”等字符串中的转义码作为单独的字符进行处理(例如从文件中读取),您将需要编写(或使用现有的)一个字符串函数来查找转义码代码并将其转换为其他值,例如将“\”后跟“n”转换为换行符(ascii 值 10)。
It is the compiler that process escape codes in string literals, not the runtime methods. This is why you can for example have "char c = '\n';" since the compiler just compiles it as "char c = 10".
If you want to process escape codes in strings such as '\' and 'n' as separate characters (eg read as such from a file), you will need to write (or use an existing one) a string function which finds the escape codes and converts them to other values, eg converting a '\' followed by a 'n' into a newline (ascii value 10).