Search code examples
c++loopsprompt

How to repeat a program when user prompted y/n


This program is supposed to encrypt and decrypt the string "myWord". Once received, it passes through the two methods to encrypt and decrypt and then returns to main. I have been trying to make it prompt the user if they want to continue or not. If they enter "n" then the loops stops and the program ends. if they enter "y" then it will repeat and they will be able to encrypt again after they are prompted for their name again. I've tried many different ways but the output continues to end up like this after I enter y:

#include <iostream>
#include <string>

using namespace std;

void encrypt(string);
void decrypt(string);

int main() {
    string myWord;

    char choice = 'y';
    while (choice == 'y') {
        cout << "Enter a name: ";
        getline(cin, myWord);
        encrypt(myWord);
        cout << "Would you like to encrypt again? (y/n): ";
        cin >> choice;
        if(choice == 'n') {
            return 0;
        }
        system("pause");
    }
    return 0;
}

void encrypt(string encrypting) { 
    for (int i = 0; encrypting[i] != '\0'; i++) {
        encrypting[i] = encrypting[i] + 1;
    }
    cout <<"Encrypted: " << encrypting << endl;
    decrypt(encrypting);
}

void decrypt(string decrypting) {
    for (int i = 0; decrypting[i] != '\0'; i++) {
        decrypting[i] = decrypting[i] - 1;
    }
    cout << "Decrypted: " << decrypting << endl;
    return;
}

My output

1


Solution

  • Your issue is switching between whitespace-delimited input and line-oriented input. Since std::cin leaves the '\n' in the stream, the next call to std::getline sees that and skips ahead too.

    You need to skip to the end of the stream:

    See https://en.cppreference.com/w/cpp/string/basic_string/getline for more information.

    This should fix your problem:

    #include <limits>
    #include <ios>
    
    //...
    
    cout << "Enter a name: ";
    getline(cin, myWord);
    encrypt(myWord);
    cout << "Would you like to encrypt again? (y/n): ";
    cin >> choice;
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');