0

在主函数中,在 do while 循环中使用 getchar 会产生问题(根据我的理解)并使用 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;
}
4

1 回答 1

0

其他一些条款会有所帮助。将所有这些 if 放入一个大的 if/else if/else 循环中:

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

你很可能会得到一个你没想到的字符,比如回车。

另外,你为什么混合cin和getc?

于 2013-10-01T20:43:56.360 回答