简体   繁体   中英

End while loop for character substitution

This is taken out from Keyshanc Encryption Algorithm. https://github.com/Networc/keyshanc

My question is: How can I possibly manipulate this main method for having multiple encryption outputs with the keys chosen from the password array?

I am not able to break out of the encoding loop right at the end.

int main()
{
    string password[] = {"JaneAusten", "MarkTwain", "CharlesDickens", "ArthurConanDoyle"};

    for(int i=0;i<4;++i)
    {
        char keys[95];

        keyshanc(keys, password[i]); 

        char inputChar, trueChar=NULL;
        cout << "Enter characters to test the encoding; enter # to quit:\n";
        cin>>inputChar;

        for (int x=0; x < 95; ++x)
        {
            if (keys[x] == inputChar)
            {
                trueChar = char(x+32);
                break;
            }
        }

        while (inputChar != '#')
        {
            cout<<trueChar;
            cin>>inputChar;
            for (int x=0; x < 95; ++x)
            {
                if (keys[x] == inputChar)
                {
                    trueChar = char(x+32);
                    break;
                }
            }

        }
     }
    return 0;
}

You are taking input in two places, so you have to put two tests.

When you are in the while loop, you have to break out of the while loop, and also break out of the for(;;) loop. You can set i=5; to force the for(;;) loop to stop.

for (int i = 0; i<4; ++i)
{
    char inputChar, trueChar = 0;
    cout << "Enter characters to test the encoding; enter # to quit:\n";

    cin >> inputChar;

    if (inputChar == '#') //<== ADD THIS
        break;

    while (inputChar != '#')
    {
        cout << trueChar;
        cin >> inputChar;

        if (inputChar == '#') //<== ADD THIS to break out of for(;;) loop
        {
            i = 5;
        }

    }
}

In addition trueChar and inputChar should be initialized to 0 not NULL (although it's the same thing in this). Don't print trueChar if it's not initialized.

if (trueChar)
    cout << trueChar;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM