0

printf("%s", ...) assumes null-terminated string. If I have a string deliminated by a length, what is the best way to do?

Suppose buf is the start address of the string, n is the length of the string. I have the following code. Is it the best way to do so?

  for(int i=0;i<n;++i) {
    fputc(buf[i], stdout);
  }
user1424739
  • 11,937
  • 17
  • 63
  • 152
  • related https://stackoverflow.com/questions/2137779/how-do-i-print-a-non-null-terminated-string-using-printf – Spade 000 Mar 18 '21 at 14:44
  • C lib defines a _string_ as ending with a _null chracter_. "If I have a string deliminated by a length" is better described in C as a character array delimited by a length. It is not a _string_. – chux - Reinstate Monica Mar 18 '21 at 16:24

2 Answers2

2

You can use %.*s format specifier to specify the length to print.

#include <stdio.h>

int main(void) {
    int length = 3;
    const char* str = "123456";
    printf("%.*s\n", length, str);
    return 0;
}

This example will print 123.

Better way to print fixed-length data should be using fwrite(). printf() can do many thing, so it may be unnecessarily slow.

#include <stdio.h>

int main(void) {
    int length = 3;
    const char* str = "123456";
    fwrite(str, sizeof(*str), length, stdout);
    return 0;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • `printf("%.*s\n", length, str);` will not print to the length is a null character is encountered first. `printf("%.*s\n", 7, "abc\0xyz");` only prints `"abc"`. `fwrite()` will print all 7. – chux - Reinstate Monica Mar 18 '21 at 16:21
0

I think using fwrite is also an overkill here a you are anyway printing a string (which is a set of char). Instead you could just use putchar(), it writes to stdio by default.

while(i<n)
 putchar(buf[i++]);
CallMe RK
  • 86
  • 4