2014-11-05 151 views
0

代碼從我caesar.c文件奇怪的輸出與caesar.c

#include <stdio.h> 
#include <cs50.h> 
#include <string.h> 
#include <stdlib.h> 
#include <ctype.h> 


int main(int argc, string argv[]) 
{ 
    // get a string from the user, a non-negative integer. 
    if (argc != 2 || atoi(argv[0]) < 0) 
    { 
     printf("Usage: ./caesar cyphertext\n"); 
     return 1; 
    } 

    // create the cyphertext. 
    int cyphertext = atoi(argv[1]); 

    // declare plaintext input. 
    string plaintext = GetString(); 

    // get the plaintext encrypted using the key. 
    for (int i = 0, n = strlen(plaintext); i < n; i++) 
    { 
     if (plaintext[i] > 'A' && plaintext[i] <= 'Z') 
     { 
      plaintext[i] = (plaintext[i] - 'A' + cyphertext) % 26; 
     } 
      else if (plaintext[i] >= 'a' && plaintext[i] < 'z') 
      { 
       plaintext[i] = (plaintext[i] - 'a' + cyphertext) % 26; 
      } 
    } 
    { 
     // print out the results of the cypher and plaintext. 
     printf("%s\n", plaintext); 
    } 
    return 0; 
} 

輸出 我./caesar 13類型,然後在下一行我單詞「hello」的類型。 你好,然後返回幾個小盒子裏有小字母和數字。我不能 複製和粘貼確切的字符。

編輯:

感謝您的幫助。我清理,按您的幫助,現在當我運行check50程序

check50 2014/x/pset2/caesar caesar.c 

我收到以下錯誤:

:(encrypts "BARFOO" as "EDUIRR" using 3 as key 
    \ expected output, but not "EAUIRR\n" 

然而,當我運行了3字BARFOO作爲重點我做實際上得到的輸出爲 EAUIRR。

+3

'atoi(argv [0])'?? – BLUEPIXY 2014-11-05 02:32:57

回答

1

您在凱撒加密時犯了錯誤。

plaintext[i] = (plaintext[i] - 'A' + cyphertext) % 26; 

應該

plaintext[i] = 'A' + ((plaintext[i] - 'A' + cyphertext) % 26); 

plaintext[i] = (plaintext[i] - 'a' + cyphertext) % 26; 

應該

plaintext[i] = 'a' + ((plaintext[i] - 'a' + cyphertext) % 26); 

說明:

讓我們考慮一下明文[i] =「h」的情況。

plaintext[i] - 'a' 

使得7.( 'H' - 'A')

(plaintext[i] - 'a' + cyphertext) % 26 

使20.((7 + 13)%26)

的字符,其代碼是20,是控制代碼「DC4」,並且不可打印。

這就是爲什麼你會看到「小箱子裏有小字母和數字」。

您可以通過將代碼ot'a'添加到20來解決此問題。