1

アルファベットの後半で小文字を対称的な対応する文字に反転する小さな関数を作成しようとしています-26文字= 13/13。

a = z、b = y、c = x...

次のコードを試しましたが、何らかの理由で最初の文字でしか機能しません。

「ばんば」と入力するとします。「b」を「y」に切り替えることから始めますが、スタックして他のすべての文字も「y」に置き換え、「yyyyy」になります。

コードを少しいじってみたところ、現在の文字による依存関係を削除すると、すべての文字を安全に 1 (a = b, b = c...) 増やすことができることがわかりました。

symmetric_difference = 1; **commented out** //21 - toCrypt[i];

私が見つけた最も近いものは「文字列内の個々の文字のアルファベット値を逆にする」でしたが、奇妙で冗長に見える方法を説明しています。

誰かが私が間違っていたことを教えてもらえますか? (私がしたと仮定して)

#include <iostream>
using namespace std;

void crypto(char[]);

int  main()
{
    char toCrypt[80];

    cout << "enter a string:\n";
    cin >> toCrypt;

    crypto(toCrypt);

    cout << "after crypto:\n";
    cout << toCrypt;
}

void crypto(char toCrypt[]) // "Folding" encryption.
{
    int size = strlen(toCrypt);
    int symmetric_difference;

    for (int i = 0; i < size; i++)
    {
        symmetric_difference = 121 - toCrypt[i];    // Calculate the difference the letter has from it's symmetric counterpart.

        if (toCrypt[i] >= 97 && toCrypt[i] <= 110)  // If the letter is in the lower half on the alphabet,
            toCrypt[i] += symmetric_difference; // Increase it by the difference.
        else
        if (toCrypt[i] >= 111 && toCrypt[i] <= 122) // If it's in the upper half,
            toCrypt[i] -= symmetric_difference; // decrease it by the difference.
    }
}
4

3 に答える 3

1

あなたの例ではbamba、すべての文字が最初の if ステートメントに入ります: toCrypt[i] += symmetric_difference;

toCrypt[i] += symmetric_difference;
-> toCrypt[i] = toCrypt[i] + 121 - toCrypt[i];
-> toCrypt[i] = 121 = 'y'
于 2014-01-07T19:45:46.900 に答える
0

入力ミスがなければ、次の関数定義を試してください。

void crypto( char s[] )
{
    static const char alpha[] = "abcdefghijklmnopqrstuvwxyz"; 
    const char *last = alpha + sizeof( alpha ) - 1;

    while ( char &c = *s++ )
    {
      if ( const char *first = std::strchr( alpha, c ) ) c = *( last - ( first - alpha ) - 1 );
    }
}   

小文字を順番に並べる必要はないことを考慮してください。たとえば、私が間違っていなければ、EBCDIC には有効ではありません。

ステートメントを代用したい

const char *last = alpha + sizeof( alpha ) - 1;

為に

const char *last = alpha + sizeof( alpha ) - sizeof( '\0' );

しかし、最後はCと互換性がありません:)

于 2014-01-07T19:59:55.290 に答える