0

我正在使用这个程序来实现单字母密码。我遇到的问题是当我输入纯文本时,当满足按下回车键的条件时它不会退出循环。这是我的代码。

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()返回\r,所以你的休息永远不会真正执行。您应该将其更改为getchar()even 因为 getche 是一个非标准函数。

您甚至可以尝试在您的情况下寻找\r\n,但我猜\n如果您以后需要获取任何其他输入(不确定),它会留在缓冲区中导致问题。

于 2012-09-19T17:38:06.620 回答
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 回答
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 回答