【发布时间】:2017-04-23 12:06:41
【问题描述】:
我有一个问题,有时在字符串的末尾我得到很多?????????我不知道如何解决这个问题,而不是得到那个垃圾。 . .
USHORT length = (USHORT)d.GetLength();
if (length == 0) {
cEncodeJsonUtil->AddElement(dataHeader, L"null", false);
}
else {
WCHAR* buf = (WCHAR*)d.GetData();
//buf[length + 1] = L'\0'; //bugs like this as well as like buf[length]=L'\0';
// should I escape here or not ? is this + L'\0' ok ?S?!? Even after excaping still there is trash inside.
cEncodeJsonUtil->AddElement(dataHeader, (const WCHAR*)buf+ L'\0');
}
cEncodeJson->AddElement 只是打印出这样的元素
wprintf(L"\n\"%s\" : \"%s\"\n", pwszKey, pwszValue);
我做错了吗?打印错了?我应该使用:
swprintf(buf, L"%ls", buff); //to copy from the value I get to my own buffer?
非常感谢!
【问题讨论】:
-
可能您打印到的控制台不支持这些字符。
-
但是当它打印垃圾时,它会为 wcslen(buf) 返回一些 90 的巨大数字,它会返回 exmplae 620,在调试器中我可以看到前 90 个 wchars 来自我的字符串,然后就是垃圾
-
(const WCHAR*)buf+ L'\0'不附加终止零 -
@Vess 是的,有 wcsncpy(类似于 strncpy)
-
字符串的结尾要么标有终止符,要么没有。如果已标记,则没有理由尝试向其添加零字符。如果没有标记,则需要将长度传递给用零字符标记结尾的函数,否则它无法知道在哪里标记。因此,除了
+没有做你想做的事之外,在你只需要告诉你要使用什么的情况下,你不要使用长度是长度!
标签: c++ c printf garbage wchar