简体   繁体   中英

What is wrong with getchar (as program is exiting without a check at do while loop)?

In this in the main function the usage of getchar in do while loop is creating problem (as per what im 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;
}

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM