0

私はこのプログラムを使用してモノラルアルファベット暗号を実装しています。私が得ている問題は、プレーンテキストを入力したときに、Enterキーを押している条件が満たされたときにループから抜け出せないことです。これが私のコードです。

int main()
{
    system("cls");
    cout << "Enter the plain text you want to encrypt";
    k = 0;
    while(1)
    {
        ch = getche();
        if(ch == '\n')
        {

            break; // here is the problem program not getting out of the loop
        }
        for(i = 0; i < 26; i++)
        {
            if(arr[i] == ch)
            {
                ch = key[i];
            }
        }
        string[k] = ch;
        k++;
    }
    for(i = 0;i < k; i++)
    {
        cout << string[i];
    }
    getch();
    return 0;
}
4

3 に答える 3

3

ここでの問題はおそらく、getche()(とは異なりgetchar())複数の入力があり、Windowsを使用している場合(そうでない場合は使用しない場合cls)に最初の文字を返すだけで、EOLはでエンコードされるという事実です\r\n

何が起こるかというと、あなたの休憩が実際に実行されることは決してないので、それgetche()は戻ります。getcheは非標準関数であるため、\rに変更する必要があります。getchar()

\r代わり\nに、状況に応じてそれを探すこともできます\nが、後で追加の入力をフェッチする必要がある場合は、がバッファに残り、問題が発生する可能性があります(不明です)。

于 2012-09-19T17:38:06.620 に答える
2

C++の古いCライブラリに依存するのは厄介です。この代替案を検討してください。

#include <iostream>
#include <string>

using namespace std; // haters gonna hate

char transform(char c) // replace with whatever you have
{
    if (c >= 'a' && c <= 'z') return ((c - 'a') + 13) % 26 + 'a';
    else if (c >= 'A' && c <= 'Z') return ((c - 'A') + 13) % 26 + 'A';
    else return c;
}

int main()
{
    // system("cls"); // ideone doesn't like cls because it isnt windows
    string outstring = "";
    char ch;
    cout << "Enter the plain text you want to encrypt: ";
    while(1)
    {
        cin >> noskipws >> ch;
        if(ch == '\n' || !cin) break;
        cout << (int) ch << " ";
        outstring.append(1, transform(ch));
    }
    cout << outstring << endl;
    cin >> ch;
    return 0;
}
于 2012-09-19T17:55:58.800 に答える
2

標準のC++I/Oを使用する休閑のようなことをします。

#include <iostream>
#include <string>

using namespace std;

// you will need to fill out this table.
char arr[] = {'Z', 'Y', 'X'};
char key[] = {'A', 'B', 'C'};

int main(int argc, _TCHAR* argv[])
{
    string sInput;
    char   sOutput[128];
    int k;

    cout << "\n\nEnter the plain text you want to encrypt\n";
    cin >> sInput;

    for (k = 0; k < sInput.length(); k++) {
        char ch = sInput[k];

        for(int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++)
        {
            if(arr[i] == ch)
            {
                ch = key[i];
                break;
            }
        }
        sOutput[k] = ch;
    }
    sOutput[k] = 0;
    cout << sOutput;

    cout << "\n\nPause.  Enter junk and press Enter to complete.\n";
    cin >> sOutput[0];

    return 0;
}
于 2012-09-19T18:08:11.710 に答える