我試圖從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;
}
你嘗試使用調試器? 'if(islower)else if(islower)'? – purplepsycho
使用tolower和toupper而不是你自己的。 –
我不能用'./caesar 27'重現任何問題,除非'GetString'壞了,或者你忘記參數(你正在做'atoi(argv [1] ]),然後檢查是否存在'argv [1]')。 – molbdnilo