2016-07-04 146 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())'替换... –