2016-07-04 182 views
-3

我試圖從edx運行程序分配caesar.c編程簡介。它需要一個能夠使用凱撒加密來加密字符串的程序:因此,用戶必須輸入一個密鑰(命令行)。例如用2的鍵'A'字符需要以'C'字符加密;當您必須輸入一個大於26的字母時,問題就開始了,這是字母的數字。例如對於一個27和一個'A'字符的密鑰,程序必須返回'B'就像一個鍵1.卡住了Caesar.c

我試圖將字符的ASCII值轉換爲從0到26的字母值當鍵等於或大於26時,請使用模運算符。 它返回給我一個段錯誤。任何人都可以幫我提一些關於我的錯誤原因的建議嗎?

這裏的程序:

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

int key; 

// function for an alphabetic value with non capital letters 

int alpha_low(char c) 
{ 
    int alpha_value; 
    alpha_value = (int) c - 97; 
    return alpha_value + (key % 26); 
} 

// function to return to ascii valuee for non capital letters 

char ascii_low(char c) 
{ 
    return (char) alpha_low(c) + 97; 
} 

// function for an alphabetic value with capital letters 

int alpha_up(char c) 
{ 
    int alpha_value; 
    alpha_value = (int) c - 65; 
    return alpha_value + (key % 26); 
} 

// function to return to ascii value for capital letters 

char ascii_up(char c) 
{ 
    return (char) alpha_up(c) + 65; 
} 


int main(int argc, string argv[]) 
{ 
     int result; 
     string p; 
     key = atoi(argv[1]); 

    if(argc != 2 || key < 0) 
    { 
     printf("Usage: ./caesar key(positive integer)\n"); 
     return 1; 
    } 

    printf("Please, write a plaintext: "); 
    p = GetString(); 

    for(int i = 0, n = strlen(p); i < n; i++) 
    { 
     if (isalpha(p[i])) 
     { 
      if (islower(p[i])) 
      { 
      result = alpha_low(p[i]); 
      printf("%c", ascii_low(p[i])); 
      } 
      else if(islower(p[i])) 
      { 
       result = alpha_up(p[i]); 
       printf("%c", ascii_up(p[i])); 
      } 
     } 
    }  

    return 0; 
} 
+2

你嘗試使用調試器? 'if(islower)else if(islower)'? – purplepsycho

+0

使用tolower和toupper而不是你自己的。 –

+1

我不能用'./caesar 27'重現任何問題,除非'GetString'壞了,或者你忘記參數(你正在做'atoi(argv [1] ]),然後檢查是否存在'argv [1]')。 – molbdnilo

回答

2

凱撒字母字符應該是這樣的函數(分解在基本步驟):

int caesar_lower(int c,int key) { 
    int v = c-'a'; // translate 'a'--'z' to 0--25 
    v = v+key;  // translate 0--25 to key--key+25 
    v = v%26;  // translate key--key+25 to key--25,0--key-1 
    v = v+'a';  // translate back 0--25 to 'a'--'z' 
    return v; 
} 
+0

謝謝。你的函數同步我的兩個函數,但是當我運行該程序時,它只返回加密的低字符,而大寫字母不會被打印出來,而且單詞之間沒有空格。你有任何改進我的代碼的建議嗎?我真的不知道爲什麼它沒有考慮到大寫字母 –

+0

我解決了空間問題(實際上很愚蠢的問題)...只需要瞭解爲什麼caesar_upper函數不激活 –

+0

因爲您使用了兩次同樣的測試'if(islower())'...用'if(islower())... else if(isupper())'替換... –