Aceso
Aceso

Reputation: 1215

repeat code automatically

I wrote some code to convert any string to Morse code. The code works perfect until I try repeating it automatically.

Whether I use "while" or "do while" the code runs only once and then it terminates. Would you help to find out what the problem is?

int main ()
{
    cout<<"Enter the string: ";
    char myStr[81];
    char ch='y';

    while (ch=='Y'||ch=='y')
    {
        getString(myStr);
        toUpper(myStr,strlen(myStr));
        removeSpace(myStr);
        getMorse(myStr,strlen(myStr));
        cout<<"to repeat press Y/y";
        cin>>ch;
    }
    return 0;
}

I added the getString() function

void getString(char myStr[])
{
  cin.getline(myStr,81,'\n');
}

Upvotes: 0

Views: 220

Answers (1)

maditya
maditya

Reputation: 8886

After the user enters input, they press enter. That newline character '\n' is still in the cin stream. You need to ignore it:

cin >> ch;
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //this ignores all subsequent characters until the newline character

Upvotes: 1

Related Questions