2016-11-29 178 views
0

我想製作一個程序,它需要一個字母並使用凱撒加密將它們從一個值轉換到b。它必須使用一個字符串才能做到這一點。C語言 - 凱撒加密程序

我的問題是我的程序不會把用戶輸入的字符串。 (我試圖把人[10]放在scanf中,但這隻會導致程序崩潰 - 所以我願意把不正確的人放在那裏,以便程序可以編譯)。

#include <stdio.h> 


int main(){ 
int i=0; //setting the individual slot number for the array-- later used in the while loop 
char guy[10]; 
printf("Enter Plain Text:"); 
scanf("%s",&guy); //takes user's input-- such as "abc" and puts it into its respective slot in the array guy[10] r-right? 

while (guy[10] != '\0'){ //while loop that runs until it reaches the end of the string 
    if ((guy[i]) >= 'A' && (guy[i]<= 'Z')){ //moves capital letter values up 1 
     guy[i]=guy[i]++; //makes the current "slot" number go up 1 value. Example: a = 97 + 1 -> b = 98 
     } 
    if ((guy[i]) >= 'a' && (guy[i]) <= 'z'){// moves lower case letter values up 1 
     guy[i]=guy[i]++; 
    } 
    i++; //moves the array's interval up to the next "slot" 

} 
printf("Encrypted text is: %s",guy); 
} 
+0

,有隻有很多方法才能在C中合理實現凱撒密碼,而在本站搜索框中的[C]凱撒會產生超過一百個。關於你的代碼。 「傢伙[我]」,而不是「傢伙[10]」,應該在你的時間表達式中。 'guy',不是'&guy',應該是傳遞給'scanf'的參數。 – WhozCraig

+0

雖然這是真的,但它們都不覆蓋C語言的深度 –

回答

0

你的第一個問題是這一行:

scanf("%s",&guy); 

guy是一個數組,所以我們並不需要得到它的指針,它的名字是因爲在這種情況下指針處理。簡單地做:

(void) scanf("%s", guy); 

你的第二個問題是這一行:

while (guy[10] != '\0') 

爲WhozCraig INT他的評論中指出的那樣 - 這應該使用索引i,不10

第三個問題是,這聲明沒什麼意義:

guy[i]=guy[i]++; 

Rea可供選擇的替代品包括:

guy[i] = guy[i] + 1; 
guy[i]++; 
guy[i] += 1; 

第四個問題是你沒有處理環繞。例如。 'Z'在你的代碼中映射到什麼地方?它看起來會以「[」而不是「A」出現。

第五個問題是,scanf()可以溢出數組guy,因爲它的輸入大小是無限的。對於guy[10],我們需要做的是這樣的:

scanf("%9s", guy); 

要輸入與空間,最終「\ 0」限制爲九個字符。使用fgets()會在這種情況下一個更好的選擇,因爲它是更安全,我們不需要的scanf()的解析功率:

fgets(guy, 10, stdin); 

下面是解決這五個問題進行返工:據透露

#include <stdio.h> 

int main() { 
    char text[10]; 

    printf("Enter Plain Text: "); 
    (void) fgets(text, 10, stdin); // takes user's input -- such as "abc" and put it into its respective slots in the array 

    int i = 0; // slot index for the array 

    while (text[i] != '\0') { // loop until reach end of string 

     if (text[i] >= 'A' && text[i] <= 'Z') { // move capital letter values up 1 
      // make the letter go up 1 modulo 26. Example: A = 65 + 1 -> B = 66; Z = 90 + 1 -> A = 65 
      text[i] = ((text[i] - 'A' + 1) % ('Z' - 'A' + 1)) + 'A'; 
     } else if (text[i] >= 'a' && text[i] <= 'z') { // move lower case letter values up 1 
      text[i] = ((text[i] - 'a' + 1) % ('z' - 'a' + 1)) + 'a'; 
     } 

     i++; // move the array's index up to the next "slot" 
    } 

    printf("Encrypted text is: %s\n", text); 
}