How to print a string with embedded nulls so that “(null)” is substituted for '\0'

后端 未结 4 1454
天涯浪人
天涯浪人 2021-01-21 15:32

I have a string I composed using memcpy() that (when expanded) looks like this:

char* str = \"AAAA\\x00\\x00\\x00...\\x11\\x11\\x11\\x11\\x00\\x00...\";
<         


        
4条回答
  •  时光说笑
    2021-01-21 16:05

    From C++ Reference on puts() (emphasis mine):

    Writes the C string pointed by str to stdout and appends a newline character ('\n'). The function begins copying from the address specified (str) until it reaches the terminating null character ('\0'). This final null-character is not copied to stdout.

    To process data such as you have, you'll need to know the length. From there, you can simply loop across the characters:

    /* ugly example */
    char* str = "AAAA\x00\x00\x00...\x11\x11\x11\x11\x00\x00...";
    int len = ...; /* get the len somehow or know ahead of time */
    for(int i = 0; i < len; ++i) {
      if('\0' == str[i]) {
        printf(" (null) ");
      } else {
        printf(" %c ", str[i]);
      }
    }    
    

提交回复
热议问题