Home > OS >  how can I fix the way printf manage strings with UTF8 and s, in c?
how can I fix the way printf manage strings with UTF8 and s, in c?

Time:10-23

I am trying to print a string with non ASCII chars using c and printf, this is the program:

include <stdio.h>
void main(void){
  printf("<0123456789> BOTH %s\n","<%5s>");
  printf("<%5s>\n"," w ");
  printf("<%5s>\n"," δ ");
}

and I get

<0123456789> BOTH <%5s>
<   w >
<  δ >

So there is a problem with the size of strings. How can I get both strings with the same size?

CodePudding user response:

Your lowercase delta character is not an 8-bit value. It's represented by two bytes, so printing it with a width specifier of 5 result in it only printing in 4 visible spaces. You can see the same issue with other Greek letters.

You can further see this by printing the result of strlen(" δ ") which prints 4.

CodePudding user response:

For working with unicode you should use fwprintf instead of printf.

See also 7.24.2 Formatted wide character input/output functions.

  • Related