I am writing a simple Caesar implementation for Amharic- one of the languages widely spoken in Ethiopia. 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. 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. But couldn't make much sense. Here are my question:

  1. Why does it work for the key 0 to 5 but not above?
  2. Where does it get the additional char it prints for key grater than 5?

If it helps the sizeof wchar on my machine is 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.

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. 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归因
不隶属于 StackOverflow
scroll top