卡住Caesar.c

时间:2016-07-04 14:35:30

标签: c encryption cs50 caesar-cipher

我正在尝试从edx编程简介中运行程序分配caesar.c。它需要一个能够使用Caesar加密来加密字符串的程序:因此,用户必须输入一个密钥(命令行);例如,密钥为2 a'A'字符需要以'C'字符加密;当您必须输入大于26的键(即字母数字)时,问题就开始了。例如,对于27的键和'A'字符,程序必须像1的键一样返回'B'。

我试图将字符的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;
} 

1 个答案:

答案 0 :(得分: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;
}
相关问题