Start New Discussion within our Software Development Community

It lets me continue the loop but it won't let me enter a sentence the second time??

#include <iostream> 
#include <iomanip> 
#include <string>
#include <cctype>
using namespace std;

int main()
{
    char c, response;
    int Uc = 0, Dc=0, Vc=0, Wc=0;
    string vowels("aeiouAEIOU");

    cout << "I can count the number of upper case, lower case, vowels and words" << endl; 
do
{
    cout << "Enter a sentence: ";
    cin.get(c);

    while(c != '\n')
    { 
        {
        if(isupper(c))  
            Uc++;  
        if(isdigit(c)) 
            Dc++; 
        if(vowels.find(c) != string::npos)
            Vc++;
        if (isspace(c))
            Wc++;

        cin.get(c);
        } 
    }

     cout << setfill ('.');
     cout << "  Number of uppercase letters: " << Uc << endl; 
     cout << "  Number of digits: " << Dc << endl; 
     cout << "  Number of vowels: " << Vc << endl;
     cout << "  Number of words: " << Wc << endl;

     cout << "CONTINUE(y/n)? ";
     cin.get(response);

} while(response == 'Y' || response=='y') ;
    cout << endl;

    system("pause");
    return 0;
}

The problem is that cin.get(response); is leaving an '\n' in the buffer so when you call cin.get(c); at the beginning of the loop it pulls in the '\n'. Since '\n' stops the inner loop it never gets executed and then you are asked to continue again. To fix this you need to get rid of the '\n' in the buffer. You can use a simple hack and use cin.get() after cin.get(response); which will eat the '\n' and you can enter another sentance. I prefer to use ignore() and I use it as

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
This article has been dead for over six months. Start a new discussion instead.