0

I am trying to make this program loop and ask the user for words and a key to output a encrypted version of the string. It is working fine the first loop, it correctly outputs the encrypted the string, but when it asks again for another string and I type the input, the terminal just prints out "Enter word" infinite times.

   #include <cstdlib>
#include <iostream>
#include <vector>
#include <sstream>

using namespace std;

int main()
{
    string str = "";
    while (str != "quit")
    {
        // initialize variables
        string encptd = "";
        int key = 0;
        // ask for words
        cout << "Enter words to encrypt, enter \"quit\" to quit: ";
        getline(cin, str);

        // check if user wants to quit program
        if (str == "quit")
        {
            return 0;
        }

        string arr[8];
        int i = 0;
        stringstream ssin(str);
        while (ssin.good() && i < 8)
        {
            ssin >> arr[i];
            ++i;
        }

        // ask for key
        cout << "Enter the key: ";
        cin >> key;

        for (int i = 0; i < str.length(); i++)
        {
            if (str[i] == ' ')
            {
                encptd += ' ';
            }
            else
            {
                // encrypt words
                int value = int(str[i]) - 97;
                int enc = ((value + key) % 26) + 97;
                encptd += tolower(char(enc));
            }
        }

        string encryp[8];
        int j = 0;
        stringstream ssin2(encptd);
        while (ssin2.good() && j < 8)
        {
            ssin2 >> encryp[j];
            ++j;
        }

        for (i = 0; i < 8; i++)
        {
            printf("%-5s %-5s\n", arr[i].c_str(), encryp[i].c_str());
        }
    }

    return 0;
}
Gabriel
  • 11
  • 1
  • 1
    Does this answer your question? [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – drescherjm Jan 17 '22 at 02:22
  • I am surprised that no one has yet told you about [minimal complete examples](https://stackoverflow.com/help/minimal-reproducible-example). – Beta Jan 17 '22 at 02:23

0 Answers0