string array with garbage character at end

前端 未结 7 2090
遇见更好的自我
遇见更好的自我 2020-11-29 11:29

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:

相关标签:
7条回答
  • 2020-11-29 12:06

    It's odd that no-one has mentioned this possibility:

    char Buffer[8]; //holds the byte stream
    int i = 0;
    
    while (i < sizeof(Buffer) && (charInput = get_the_users_character()) != EOF)
    {
        Buffer[i] = charInput;
        i++;
    
        // Display a response to input
        printf("Buffer is %.*s!\n", i, Buffer);
    }
    

    This notation in the printf() format string specifies the maximum length of the string to be displayed, and does not require null termination (though null termination is ultimately the best way to go -- at least once you leave this loop).

    The while loop is more plausible than a simple if, and this version ensures that you do not overflow the end of the buffer (but does not ensure you leave enough space for a trailing NUL '\0'. If you want to handle that, use sizeof(Buffer) - 1 and then add the NUL after the loop.

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