I'm trying to make a stack application but I'm having trouble with using cin a loop that in case the user enters a different value type, it will loop again to ask for the user's input.
I have tried using cin.ignore() but still, it didn't work.
#include <iostream>
#include <stack>
#include <cstdlib>
#include <cctype>
usingnamespace std;
int main()
{
stack<int> n;
int var,ctr=-1;
int* start;
char choice;
do{
while(1) // here goes my problem, in this loop
{
cout<<"Enter an integer: ";
if(cin>>var)
break;
}
n.push(var);
if (n.size()==0)
start=&n.top();
cout<<"Do you want to enter another integer? (Y/N) : ";
cin>>choice;
system("cls");
}while (choice=='Y' | choice=='y');
ctr=n.size();
cout<<"Display input(s)"<<endl;
while (!n.empty())
{
for (int i=ctr-1; i>=0;i--)
{
int *ptr=&n.top()-i;
cout<<*ptr<<" ";
}
cout<<"\nPopping.. "<<n.top();
n.pop();
ctr--;
cout<<endl;
if (ctr==0)
cout<<"\nSTACK is now empty!";
}
return 0;
}
choice (line 12) is uninitialized.
If you execute the break at line 18, you will exit the inner loop and the while condition at line 28 will be evaluated against an uninitialized value, which is pretty much guaranteed to be false taking you back to the top of the loop.
while(1) // here goes my problem, in this loop
{
cout<<"Enter an integer: ";
if(cin>>var) // cin success
break;
// cin is broken
cin.clear();
cin.inore(80,'\n');
}
It would be "better" to formulate your loop: while (!(cin >> var)) //...
When you entered a non-numeric, cin couldn't remove it from cin's buffer so it stayed there along with the newline. cin.clear resets cin's error flags. cin.ignore eats everything up to and including the newline so that cin's buffer is clear for the next input.