0

私のコードが AZ 0-9 の文字を含まない文字列を受け入れないのはなぜですか? これをたとえば「aaaaa[[[[[[」」のように暗号化すると、エラーが発生します。スペースなども受け入れ、az、AZ、0-9 以外のものをスキップできるようにコードが必要です。

私の最後のelseステートメントがうまくいかないのはなぜですか?

例えば:

"a       a" shift 1 

する必要があります

"b       b"

私のコード:

#include <stdio.h>

int main (){

    char word[20];
    int rotx;

    printf("enter string\n");
    scanf("%s", word);

    printf("enter rotations\n");
    scanf("%d", &rotx);

    encrypt(word, rotx);

    return 0;
}

void encrypt (char word[], int rotx){

    int w = strlen(word) - 1;
    int i = 0;

    for ( ; i <= w; i++)
        if ((word[i] + rotx) >= 65 && (word[i] + rotx) <=90)
        {
                word[i] += (rotx);
        }
        else if ((word[i] + rotx) >= 97 && (word[i] + rotx) <=122)
        {
                   word[i] += (rotx);
        }
        else if ((word[i] + rotx) >= 48 && (word[i] +rotx) <= 57)
        {
                word[i] += (rotx);
        }
        else if ((word[i] + rotx) > 90 && (word[i]+rotx) <97)
        {
                word[i] = 64 + (rotx - (90-word[i]));
        }
        else if ((word[i] + rotx) > 122)
        {
                word[i] = 96 + (rotx - (122-word[i]));
        }
        else 
        {
        continue;
        }
}
4

3 に答える 3

2

正直なところ、あなたが何をしているのかわかりません。これは、シーザー暗号が私が読んだウィキペディアに基づいていると私が信じているコードです。デモンストレーション上の理由で有害な非構文上の欠陥を誰かが見つけた場合は、私に知らせてください。

PS、「 https://www.kernel.org/doc/Documentation/CodingStyle 」を読むことを検討してください。それはあなた(そして私)に大いに役立ちます。PS: 上記のコーディング スタイルを破っても、偽善者にはなりません。自分に最も適したスタイルを選択するだけです。

コーディングに 5 分かかりました。

#include <stdio.h>
#include <string.h>

void encrypt(char *res, char *word, int rot)
{
    int len;
    int i;
    int tmp;

    len = strlen(word);

    for (i = 0; i < len; ++i) {
        tmp = word[i] - 'a';
        tmp += rot;
        tmp %= ('z' - 'a');
        res[i] = tmp + 'a';
    }

    res[len] = 0;
}

void decrypt(char *res, char *word, int rot)
{
    int len;
    int i;
    int tmp;

    len = strlen(word);

    for (i = 0; i < len; ++i) {
        tmp = word[i] - 'a';
        tmp -= rot;
        tmp %= ('z' - 'a');
        res[i] = tmp + 'a';
    }

    res[len] = 0;
}

int main()
{
    char word[20];
    char result[20];
    char decode[20];
    int rot;

    printf("enter a word: ");
    scanf("%s", word);

    printf("enter rotations: ");
    scanf("%d", &rot);

    encrypt(result, word, rot);    

    printf("result: %s\n", result);

    decrypt(decode, result, rot);

    printf("decode: %s\n", decode);

    return 0;
}
于 2013-04-02T02:23:04.487 に答える
1

空白scanf()を読み取らないので、次のスタイルに変更します。

scanf("%[^\n]", word);

gets()また、特に目的がセキュリティを提供する場合は、推奨されておらず、その使用は危険であるため、使用しないでください。

また、そのような精巧な関数は必要ありませんencrypt()。以下に示すループは、Caesar Cipher を実装するのに十分です。

for ( ; i <= w; i++)
  {     
     word[i] +=rotx;
  }
于 2013-04-02T02:20:34.683 に答える