0

In this in the main function the usage of getchar in do while loop is creating problem (as per what i m figuring out) and using getch resolves it..plz help why so..

 #include <iostream>
 #include <cstring>
 #include <stdio.h>

using namespace std;

const int size = 10;

int main()
{
    int stack[size];
    int top = -1;
    char ch;
    char chh;
    do {
        cout << "what you want to do? 1:Push,2:Pop,3:Display \n";
        cin >> ch;

        if (ch == '1')
        {
            int a;
            cout << "enter element to be entered";
            a = getchar();
            int r = push(stack, &top, a);
            if (r == -1) cout << "array already full \n";
        }

        if (ch == '2')
        {
            pop(stack, &top);
        }
        if (ch == '3')
        {
            display(stack, &top);
        }
        cout << "enter y to continue";
        chh = getchar();
    } while (chh == 'y');

    return 0;
}
David G
  • 94,763
  • 41
  • 167
  • 253
  • 3
    possible duplicate of [getchar() doesn't work well?](http://stackoverflow.com/questions/8442644/getchar-doesnt-work-well) – Natan Streppel Oct 01 '13 at 20:32

1 Answers1

0

Some else clauses will help. Put all those if's into one big if/else if/else loop:

if (ch == '1') { ... }
else if (ch == '2') { ... }
else if (ch == '3') { ... }
else { /*print out the bad char*/ }

You're likely getting a character that you're not expecting, like a carriage return.

Also, why are you mixing cin and getc?

Paul Rubel
  • 26,632
  • 7
  • 60
  • 80