本文介绍了字符指针给我一些真正奇怪的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我运行示例代码,wordLength是7(因此输出7)。但是我的char数组在它的末尾有一些很奇怪的字符。
When I run the example code, the wordLength is 7 (hence the output 7). But my char array gets some really weird characters in the end of it.
wordLength = word.length();
cout << wordLength;
char * wordchar = new char[wordLength]; //new char[7]; ??
for (int i = 0; i < word.length(); i++) //0-6 = 7
{
wordchar[i] = 'a';
}
cout << wordchar;
输出:7aaaaaaa²²²||||||D╩2|♀
The output: 7 aaaaaaa²²²²¦¦¦¦¦ÂD╩2¦♀
希望的输出是:aaaaaaa ...什么是垃圾后面?
Desired output is: aaaaaaa... What is the garbage behind it?? And how did it end up there?
推荐答案
您应该添加 \0
char * wordchar = new char[wordLength +1];
//add chars as you have done
wordchar[wordLength] = `\0`
原因是C字符串是空结束的。
The reason is that C-strings are null terminated.
这篇关于字符指针给我一些真正奇怪的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!