简体   繁体   English

Scanf和printf返回不同的unicode字符

[英]Scanf and printf return different unicode characters

I need to make a program that reads and writes Greek letters. 我需要制作一个读写希腊字母的程序。 Since Greek is not in ASCII, I set the console locale to UTF-8. 由于希腊语不是ASCII,我将控制台语言环境设置为UTF-8。 I managed to make some strings work in this multibyte mess, until i got to the part where i need user input 我设法在这个多字节的混乱中使一些字符串工作,直到我到达我需要用户输入的部分

So,ill only post the problematic part 所以,生病只发布有问题的部分

while(1) {
    char inputc[50]; 
    memset(inputc,'\0',50);
    scanf("%s",inputc)
    printf("%s",inputc);
}

With any greek character, this will print something different than the input. 对于任何希腊字符,这将打印与输入不同的内容。 Also, if I do printf("%d",inputc[i]); 另外,如果我做printf("%d",inputc[i]); for each element to get the int value (says negative for greek letters), I get a different value than reading the same character from a literal. 对于每个元素来获取int值(对于希腊字母说是负数),我得到的值与从文字中读取相同字符的值不同。

the command used is SetConsoleOutputCP(CP_UTF8); 使用的命令是SetConsoleOutputCP(CP_UTF8);

That only affects stdout (printf). 这只影响stdout(printf)。 To set stdin (scanf) as well you would need to also SetConsoleCP(CP_UTF8) . 要设置stdin(scanf),您还需要SetConsoleCP(CP_UTF8) If you set one but not the other then the input and output characters will naturally differ. 如果您设置了一个而不是另一个,则输入和输出字符自然会有所不同。

However, please be aware that there are serious bugs in the Windows Console when set to code page 65001/CP_UTF8 (or generally any multi-byte code page that doesn't have special support, ie those that aren't legacy locale-default code pages). 但是,请注意,当设置为代码页65001 / CP_UTF8时,Windows控制台中存在严重错误(或者通常是任何没有特殊支持的多字节代码页,即那些不是旧版语言环境的默认代码页)。 Windows reports byte counts incorrectly in this state, leading to print calls that mangle and repeat output, and scan calls that hang. Windows在此状态下报告字节数不正确,导致打印调用错误并重复输出,并扫描挂起的调用。 This is not generally a feasible way of getting Windows programs to talk Unicode. 这通常不是让Windows程序与Unicode通信的可行方法。

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

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