简体   繁体   English

Printf打印错误的特殊字符

[英]Printf prints wrong special character

I am working in a C/C++ code that casts a char to its integer value and then needs to print it back to its char value. 我正在使用C / C ++代码,该代码将char转换为其整数值,然后需要将其打印回其char值。

But, when I try to print an "Extended ASCII" character using the printf function, it shows a different character and I can't figure out what's wrong. 但是,当我尝试使用printf函数打印“扩展的ASCII”字符时,它显示了一个不同的字符,我无法弄清楚出了什么问题。

int charInt = (int) 'á'; // -31
char casted = (char) charInt;
printf("%c\n", casted); // ß

If I debug the code (I'm using Visual Studio 2017), the variable ' casted ' shows the correct 'á' value in IntelliSense. 如果我调试代码(我使用的是Visual Studio 2017),则变量' casted '在IntelliSense中显示正确的'á'值。

I tested some different ways of printing this character, but it always has the same result: 我测试了几种不同的打印此字符的方法,但结果始终相同:

printf("test: %d\n", (signed char)'á');   // -31
printf("test: %d\n", (unsigned char)'á'); // 225
printf("test: %c\n", -31); // ß
printf("teste: %s\n", "á"); // ß
printf("test: %c\n", 225); // ß
printf("test: %d\n", 'á'); // -31
putc(-31, stdout); // ß

What I am doing wrong ? 我做错了什么?

It was a locale problem, as said in the comments of my question. 正如我对问题的评论中所说,这是一个语言环境问题。

I just needed to use setlocale() and the output in the console worked. 我只需要使用setlocale(),控制台中的输出就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM