简体   繁体   English

wchar在C中执行简单凯撒密码的实现

[英]wchar implementation of a simple Caesar cipher in C

I am writing a simple Caesar implementation for Amharic- one of the languages widely spoken in Ethiopia. 我正在为Amharic(埃塞俄比亚广泛使用的一种语言)编写一个简单的Caesar实现。 Here is the code 这是代码

main(){
         setlocale(LC_ALL, " ");
         int i, key=0;
         wchar_t message[20];
         wprintf(L"Enter message:>");
         fgetws(message, sizeof(message), stdin);
         wprintf(L"Enter cipher key:>");
         wscanf(L"%d", &key);
         /* basic input validation goes here */
         for(i=0;message[i]!='\0'; i++){
                 message[i]=message[i]+key;
          }
       wprintf(L"The cipher is: %ls", message);
       wprintf(L"\n");
  return 0;
   }

The code compiles without a warning. 代码编译时没有警告。 Works fine if key is less or equal to 5. The problem comes when key value is 6 and above. 如果key小于或等于5,则工作正常。如果key值为6或更高,则会出现问题。 It prints one additional char so far as I tested it. 据我测试,它会再打印一个字符。 I ran it through gdb to see where it's picking up the additional char. 我在gdb中运行了它,以查看它在哪里拾取其他字符。 But couldn't make much sense. 但这没有多大意义。 Here are my question: 这是我的问题:

  1. Why does it work for the key 0 to 5 but not above? 为什么它对于0到5键而不是以上键有效?
  2. Where does it get the additional char it prints for key grater than 5? 它会从哪里获得打印出来的用于键式刨丝器的额外字符,而不是5?

If it helps the sizeof wchar on my machine is 4byte. 如果有帮助,我机器上的wchar大小为4byte。

Thank you 谢谢

EDIT: 编辑:

sample input: 样本输入:

                message: ተደለ
                key: 6 
                output: ቶዶሎ 0010
                output I expect ቶዶሎ  

The 0010 is displayed like those chars without a corresponding symbol on the unicode table. 0010像那些字符一样显示,但在unicode表上没有相应的符号。

Thanks again. 再次感谢。

The extra char you see is the wide-char newline ( 0x000a ) that is kept at the end of the string you read with fgetws and that you shift by 6 chars, resulting in 0x0010 . 您看到的额外字符是宽字符换行符( 0x000a ),该换行符保留在使用fgetws读取的字符串的末尾,并且每移位6个字符,结果为0x0010 That doesn't seem to be a printable character and the terminal decides to print the character code as plain hex numbers. 这似乎不是可打印的字符,终端决定将字符代码打印为纯十六进制数字。

Remove the trailing new-line before shifting or shift only printable characters. 在转移或仅转移可打印字符之前,请删除尾随的换行符。

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

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