Что не так с getchar (поскольку программа завершается без проверки в цикле do while)?

В этой основной функции использование getchar в цикле do while создает проблему (согласно тому, что я выясняю), и использование getch решает ее.. Пожалуйста, помогите, почему так..

 #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;
}

person Anuvrat Chitranshi    schedule 01.10.2013    source источник
comment
возможный дубликат getchar() не работает?   -  person Natan Streppel    schedule 02.10.2013


Ответы (1)


Некоторые другие пункты помогут. Поместите все эти if в один большой цикл if/else if/else:

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

Скорее всего, вы получите символ, которого не ожидаете, например возврат каретки.

Кроме того, почему вы смешиваете cin и getc?

person Paul Rubel    schedule 01.10.2013