2014-04-28 296 views
-1
#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 


void encrypting(char cipher[25], int shift, int num) 
{ 
    int i; 
    for (i = 0; i < num; i++) 
    { 
     if (cipher[i] >= 'A' && cipher[i] <= 'Z') 
     { 
      cipher[i] = (char)(((cipher[i] + shift - 'A' + 26) % 26) + 'A'); 
     } 
     else if (cipher[i] >= 'a' && cipher[i] <= 'z') 
     { 
      cipher[i] = (char)(((cipher[i] + shift - 'a' + 26) % 26) + 'a'); 
     } 
    } 
} 

void decrypting(char cipher[25], int shift, int num) 
{ 
    inti; 
    for (i = 0; i < num; i++) 
    { 
     if (cipher[i] >= 'A' && cipher[i] <= 'Z') 
     { 
      cipher[i] = (char)(((cipher[i] - shift - 'A' + 26) % 26) + 'A'); 
     } 
     else if (cipher[i] >= 'a' && cipher[i] <= 'z') 
     { 
      cipher[i] = (char)(((cipher[i] - shift - 'a' + 26) % 26) + 'a'); 
     } 
    } 
} 

int main() 
{ 
    char text[10]; 
    static const char encrypt[] = "2"; 
    static const char decrypt[] = "1"; 
    int shift; 
    char cipher[25]; 
    int result1; 
    int result2; 
    int num; 
    int i; 



    printf("Enter operation: encrypt or decrypt/n"); 
    printf("Press 1 to Encrypt or 2 to Decrypt"); 
    scanf("%c", &text); 
    printf("Enter shift key"); 
    scanf("%d", &shift); 
    printf("Enter text to encrypt/decrypt"); 
    fflush(stdin); 
    scanf("%c", &cipher); 

    num = strlen(cipher); 

    result1 = strcmp(text, encrypt); 
    result2 = strcmp(text, decrypt); 

    if (result1 == 0) 
    { 
     decrypting(cipher, shift, num); 
    } 
    else { exit(0); } 

    if (result2 == 0) 
    { 
     encrypting(cipher, shift, num); 
    } 
    else { exit(0); } 

    printf("Result"); 
    printf("%d", cipher); 
} 

程序在用戶輸入密碼文本後意外終止。我不知道現在的問題是什麼。任何人都可以解釋什麼是我的代碼現在的問題?所有的幫助表示讚賞。C程序意外終止

+2

請系統縮進您的代碼並避免將縮進字符作爲縮進字符,至少對於發佈在SO上的代碼。 –

回答

0

因爲您在printf("Result");之前撥打exit(0);,無論用戶想要加密還是解密。更改:

else{exit(0);} 

if(result2 == 0) 

要:

else if(result2 == 0) 

那麼它只會調用exit(0);如果他們選擇了既不加密也不解密。


此外,printf("%d",cipher);將無法​​打印字符串。您需要使用%s轉換說明符而不是%d

+0

我根據您的建議更改了我的代碼,現在輸出的是數字,而不是字符 – user1852728

+0

@ user1852728:您還需要在'printf'中將'%d'轉換說明符更改爲'%s';否則,它會嘗試打印一個'd'ecimal數字而不是's'字符串。 – icktoofay

+0

我已經改變了printf(「%d」,cipher);到printf(「%s」,密碼); 加密/解密現在只適用於第一個字符。 – user1852728

1

%c格式字符串scanf中的轉換說明符不會丟棄前導空格字符。這意味着,換行符'\n'將在緩衝區中留下以下scanf調用後 -

scanf("%d", &shift); 

這換行符將在未來scanf調用來讀 -

scanf("%c", &cipher); 

這是因爲它是不確定的行爲在輸入流上調用fflush。它僅針對輸出流定義。這意味着下面的語句是錯誤的 -

fflush(stdin); 

我建議你使用fgets讀取輸入字符串,然後提取該字符串的字符。此外,輸出換行符以立即在屏幕上打印消息。

+1

請注意,Microsoft定義了'fflush(stdin);'的行爲,即使C標準沒有。 –

+0

是的,甚至我的系統上的fflush的手冊頁(Ubuntu 14.04)都說 - 對於輸入流,fflush()丟棄從底層文件中獲取但未被應用程序佔用的任何緩衝數據。流的開放狀態不受影響。「但我已經讀過,它不是便攜式的。 – ajay