因此,我有一个使用此代码将数据写入数据文件的c Windows程序。
fprintf(fo,"\xbf%06d",num) ;
它工作正常,但在某些中文计算机上,其行为却有所不同。
我用C语言编写了一个小测试程序,并在Borland C和Mingw中对其进行了编译。
#include <stdio.h>
void main(void) {
int i = 0 ;
unsigned char b[100] ;
sprintf(b,"\xbf%d",12345) ;
printf("\n%s\n",b) ;
while (b[i])
printf(" %02X",b[i++]) ;
printf("\n") ;
}
在我的计算机上,输出为:
┐12345
BF 31 32 33 34 35
但是,如果我让我的中国客户在他的计算机上对其进行测试,则它对于Borland版本的工作方式会有所不同:
输出为:
?d
BF 25 64
显然,xbf和?组合成一个汉字。
在中国,使用mingw编译的程序的输出为:
?2345
BF 31 32 33 34 35
此处,格式一次解析一个字节。
正确的行为是哪一个?
其他C / C ++编译器如何处理呢?
最佳答案
我不知道您的Borland编译器发生了什么,但是使用宽字符处理诸如中文这样的扩展字符:
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
int main(void)
{
int i = 0 ;
wchar_t b[100] ;
setlocale(LC_ALL, "");
swprintf(b, 100, L"\xbf%d", 12345);
wprintf(L"\n%s\n", b);
while (b[i])
wprintf(L" %02X", b[i++]);
wprintf(L"\n");
return 0;
}
关于c - printf格式的非ASCII字符的正确行为是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49334793/