?
Solved

loop not working properly

Posted on 2011-05-09
2
Medium Priority
?
258 Views
Last Modified: 2012-05-11
Hi, my while loop is not functioning properly.

I am able to enter a word and the program checks to see if it's a palindrome.

However,On the second try, I am not able to enter a sentence. it's says automatically that's a palindrome without waiting for me to enter the sentence.

what's wrong with my code and how can I fix it?

This is my output:
Enter a sentence:hannah
It's a palindrome
CONTINUE (y/n)? y
Enter a sentence:It's a palindrome
CONTINUE (y/n)?
#include<iostream>

using namespace std;

template<class T, int n>
class Stack
{private: T x[n];int counter;
public: void ClearStack(){counter =0;}
		bool FullStack(){if(counter ==n) return true;
						 else return false;}
		bool EmptyStack(){if (counter == 0) return true;
						  else return false;}
		void Push(T a){x[counter]=a; ++counter;}
		char Pop(T a){counter--; return x[counter];}
};


int main()
{
	char ans='y';
	
	Stack<char,80> LR;
	Stack<char,80> RL;
	Stack<char,80> Temp;

	LR.ClearStack(); RL.ClearStack(); Temp.ClearStack();

	
	char c,c1,c2;

	while(ans=='y')
	{
	
	cout<<"Enter a sentence:";
	while(cin.get(c), c!='\n')
		{if(isalpha(c))
			{c=toupper(c); LR.Push(c);Temp.Push(c);}
		}

	while(!Temp.EmptyStack())
		{c=Temp.Pop(c);RL.Push(c);}

	while(!LR.EmptyStack())
		{c1=LR.Pop(c); c2=RL.Pop(c);
		if(c1 != c2) break;}

	if(LR.EmptyStack() == true) cout<<"It's a palindrome"<<endl;
	else cout<<"It's not a palimdrome"<<endl;

	


	cout<<"CONTINUE (y/n)? ";
	cin>>ans;
	ans=tolower(ans);

	

	}

return 0;}

Open in new window

0
Comment
Question by:pgmerLA
2 Comments
 
LVL 33

Assisted Solution

by:phoffric
phoffric earned 800 total points
ID: 35725843
>> On the second try, I am not able to enter a sentence. ... without waiting for me to enter the sentence.

Typically, when you see this happening on input, it is caused by a mixture of cin and other mechanisms to get the input. Often in one input method, there is a leftover newline in the buffer. If you try to be consistent in your input, then you should wait for input. If there is a newline in the buffer, and you hit an input method that actually has data ready to read (e.g., a newline), then there is no reason to wait.

Here's a quote that may help: "If the delimiting character is found, it is not extracted from the input sequence and remains as the next character to be extracted. Use getline if you want this character to be extracted (and discarded)."
       http://www.cplusplus.com/reference/iostream/istream/get/
0
 
LVL 6

Accepted Solution

by:
theKashyap earned 1200 total points
ID: 35726285
The problem is that cin has some leftovers from the sentence reading part cin.get(c); which goto the answer reading part cin>>ans;.
I've modified the code below to illustrate what's actually happening:
    while (ans=='y') {

        cout<<"Enter a sentence:";
        while (true) {
            cin.get(c);
            printf("\ngot->'%c'\n", c);
            if(c == '\n')
                break;

            if (isalpha(c)) {
                c=toupper(c); LR.Push(c); Temp.Push(c);
            }
        }
        // cin.clear();
        // cin.sync();

        while (!Temp.EmptyStack()) {
            c=Temp.Pop(c); RL.Push(c);
        }

        while (!LR.EmptyStack()) {
            c1=LR.Pop(c); c2=RL.Pop(c); if (c1 != c2) break;
        }

        (LR.EmptyStack())?  cout<<"It's a palindrome"<<endl : cout<<"It's not a palimdrome"<<endl;

        cout<<"CONTINUE (y/n)? "<<flush;
        cin>>ans;
        // cin.clear();
        // cin.sync();
        ans=tolower(ans);
    }

Open in new window


OUTPUT:
Enter a sentence:aa

got from user -- '97' --
got from user -- '97' --
got from user -- '10' --
It's a palindrome
CONTINUE (y/n)? y
Enter a sentence:
got from user -- '10' --       <-- leftover newline char from cin >> ans;
It's a palindrome
CONTINUE (y/n)? y
Enter a sentence:
got from user -- '10' --       <-- leftover newline char from cin >> ans;
It's a palindrome
CONTINUE (y/n)? n

What's happening here:
When you type "y\n" in response to "CONTINUE (y/n)?", cin
- reads 'y'
- places it in ans
- leaves '\n' inside the stream.
Now when cin.get(c) is executed again, cin reads the leftover \n. Rest is clear.

What you need to do is clear the cin after each read.

This is done by following lines:
        cin.clear();
        cin.sync();
Just uncomment these in the code I posted above. Here is sample output:

Enter a sentence:aa

got from user -- '97' --
got from user -- '97' --
got from user -- '10' --
It's a palindrome
CONTINUE (y/n)? y
Enter a sentence:as

got from user -- '97' --
got from user -- '115' --
got from user -- '10' --
It's not a palimdrome
CONTINUE (y/n)? y
Enter a sentence:asddsa

got from user -- '97' --
got from user -- '115' --
got from user -- '100' --
got from user -- '100' --
got from user -- '115' --
got from user -- '97' --
got from user -- '10' --
It's a palindrome
CONTINUE (y/n)? n

See this very good article on flushing input streams: http://www.daniweb.com/software-development/cpp/threads/90228
0

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

615 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question