简体   繁体   English

使用 cout API 时出现乱码 output

[英]Garbled character output when using cout API

I am trying to run this simple code in VS 2015我正在尝试在 VS 2015 中运行这个简单的代码

#include "stdafx.h"
# include <iostream>

int main()
{
    char * szOldPath = "\"C:\icm\scripts\StartupSync\runall.bat\" nonprod"; 
    std::cout << szOldPath << std::endl;

    return 0;
}

However, the output of szOldPath is not proper and the console is printing--但是,szOldPath的output不正确,控制台正在打印——

unall.bat" nonprodupSync

I suspect this might be because of Unicode and I should be using wcout.我怀疑这可能是因为 Unicode 我应该使用 wcout。 So I disabled Unicode by going to Configuration Properties -> General --> Character Set and tried setting it to Not Set or Multi Byte.所以我通过转到配置属性->常规->字符集禁用了 Unicode,并尝试将其设置为未设置或多字节。 But still running into this issue.但仍然遇到这个问题。

I understand it is not good to disable UNICODE but I am trying to understand some legacy code written in our company and this experiment is a part of this exercise,is there any way I can get the cout command to print szOldPath successfully?我知道禁用 UNICODE 不好,但我正在尝试理解我们公司编写的一些遗留代码,这个实验是这个练习的一部分,有什么办法可以让 cout 命令成功打印 szOldPath?

Your issue has nothing to do with Unicode.您的问题与 Unicode 无关。

\r is the escape sequence for a carriage return. \r是回车的转义序列 So, you are printing out "C:\icm\scripts\StartupSync , and then \r tells the terminal to move the cursor back to the beginning of the current line, and then unall.bat" nonprod is printed, overwriting what was already there.因此,您打印出"C:\icm\scripts\StartupSync ,然后\r告诉终端将 cursor 移回当前行的开头,然后打印unall.bat" nonprod ,覆盖已经存在的内容那里。

You need to escape all of the \ characters in your string literal, just like you had to escape the " characters.您需要转义字符串文字中的所有\字符,就像您必须转义"字符一样。

Also, your variable needs to be declared as a pointer to const char when assigning a string literal to the pointer.此外,在将字符串文字分配给指针时,您的变量需要声明为指向const char的指针。 This is enforced in C++11 and later:这在 C++11 及更高版本中强制执行:

#include "stdafx.h"
#include <iostream>

int main()
{
    const char * szOldPath = "\"C:\\icm\\scripts\\StartupSync\\runall.bat\" nonprod"; 
    std::cout << szOldPath << std::endl;

    return 0;
}

Alternatively, in C++11 and later, you can use a raw string literal instead to avoid having to escape any characters with a leading \ :或者,在 C++11 及更高版本中,您可以使用原始字符串文字来避免必须使用前导\转义任何字符:

const char * szOldPath = R"("C:\icm\scripts\StartupSync\runall.bat" nonprod)"; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM