首页 > 解决方案 > 如何在 C 中打印出特殊字符,如 å、ä、ö?

问题描述

例如,如果我尝试打印出“Ä”,我会得到这个字符:õ。我该如何解决?

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
int main (){

char name[20];

printf("Enter first name: ");
scanf("%s", name);

if(strcmp(name, "Carl") == 0){
    printf("Carl är bra!");
}
else{
    printf("Kung!");
}
return 0;
}

(顺便说一句,我使用的是代码::块)

标签: cspecial-characters

解决方案


在 Windows 上,将控制台模式设置为 UTF16 并使用wprintf宽字符串文字而不是printf.

#include <io.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int main() {

    _setmode(_fileno(stdout), _O_U16TEXT);  // this is windows specific

    wprintf(L"Carl är bra!");
    return 0;
}

但是,正如我在关于在源代码中保留 unicode 字符的评论中提到的那样。\uNNNN最好只使用转义序列内联 unicode 字符。使用如下打印语句。

    wprintf(L"Carl \u00e4r bra!");   //0x00E4 is 'ä'

推荐阅读