Why do I get garbage value when output character array to console?

后端 未结 2 662
一生所求
一生所求 2020-12-20 06:18

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         


        
相关标签:
2条回答
  • 2020-12-20 07:08

    Because you don't null terminate your buffer, std::cout.operator<<(char*) will try to find \0 as its terminating character.

    As pointed out in comments, feel free to append that \0 to the end of your buffer :).

    0 讨论(0)
  • 2020-12-20 07:22

    ScarletAmaranth is right. C style strings (an array of char) must finish with the char '\0'. That's the way functions that play with char arrays (cout in this case) know when the string finish in memory. If you forget the '\0' character at the end of the array, cout prints all the chars in the array and then goes on printing any data in memory after the array. These other data is rubbish, and that's why you see these strange characters.

    If you use the string type (more C++ style) instead of char arrays, you won't have this problem because string type don't use '\0' as a string delimiter.

    On the other hand, you don't see rubbish when use a loop to iterate over the 100 elements of the array just because you only print these 100 chars. I mean, you control exactly what you are printing and know when to stop, instead of leaving the cout function figure out when to stop printing.

    0 讨论(0)
提交回复
热议问题