我试图从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