为什么当输出字符数组到控制台时,我得到垃圾值? [英] Why do I get garbage value when output character array to console?
本文介绍了为什么当输出字符数组到控制台时,我得到垃圾值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我总是得到一个垃圾值,像这样'Íýýýý«««««««îþîþ'在结束时,当我输出我的数组。我做错了什么?
I always get a garbage value like this 'Íýýýý««««««««îþîþ' at the end when i output my array. What am I doing wrong?
void func()
{
const int size = 100;
char * buffer = new char[size];
for(int i=0; i<size; i++)
buffer[i] = ' ';
cout<<buffer;
}
然而,如果我使用for循环输出缓冲区,值
However if I use a for loop to output the buffer, there is no garbage value.
推荐答案
因为你不是null终止你的缓冲区, std :: cout.operator& <(char *)
将尝试找到 \0
作为其结束符。
Because you don't null terminate your buffer, std::cout.operator<<(char*)
will try to find \0
as its terminating character.
正如评论中所指出的,随意将 \0
附加到缓冲区的末尾:) 。
As pointed out in comments, feel free to append that \0
to the end of your buffer :).
这篇关于为什么当输出字符数组到控制台时,我得到垃圾值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文