末尾带有垃圾字符的字符串数组 [英] string array with garbage character at end
本文介绍了末尾带有垃圾字符的字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个char数组缓冲区,用于存储用户将要输入的字符.我的以下代码可以运行,但是有一些我无法弄清的故障:
I have a char array buffer that I am using to store characters that the user will input one by one. My code below works but has a few glitches that I can't figure out:
- 当我执行printf来查看Buffer中的内容时,它确实填满了,但是最后我得到了垃圾字符
- 即使被声明为char Buffer [8],它也不会停止在8个字符处;
有人可以向我解释发生了什么,也许我该如何解决?谢谢.
Can somebody please explain to me what is going on and perhaps how I could fix this? Thanks.
char Buffer[8]; //holds the byte stream
int i=0;
if (/* user input event has occurred */)
{
Buffer[i] = charInput;
i++;
// Display a response to input
printf("Buffer is %s!\n", Buffer);
}
输出:
tagBuffer is 1┬┬w!
tagBuffer is 12┬w!
tagBuffer is 123w!
tagBuffer is 1234!
tagBuffer is 12345!
tagBuffer is 123456=!
tagBuffer is 1234567!
tagBuffer is 12345678!
tagBuffer是123456789!
tagBuffer is 123456789!
推荐答案
您必须以\ 0字符结束字符串.这就是为什么它们被称为零终止字符串.
You have to end the string with a \0 character. That's why they are called zero terminated strings.
明智的是分配1个额外的char来容纳\ 0.
It is also wise to allocate 1 extra char to hold the \0.
这篇关于末尾带有垃圾字符的字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文