edxのプログラミング入門からcaesar.cというプログラム割り当てを実行しようとしています。シーザー暗号化を使用して文字列を暗号化できるプログラムが必要です。したがって、ユーザーはキー(コマンドライン)を入力する必要があります。例えば2のキーを持つ 'A'文字は 'C'文字で暗号化する必要があります。アルファベット文字の数である26を超えるキーを入力する必要があるときに問題が発生します。たとえば27のキーと 'A'文字の場合、プログラムは1のように 'B'を返さなければなりません。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'が壊れていないか、またはパラメータを忘れていない限り、segfaultを引き起こすことはできません(atoi(argv [1] argv [1] 'が存在するかどうかを調べる前に)。 – molbdnilo