getchar 有什么问题(因为程序在没有检查的情况下退出循环)



在主函数中,在 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;
}

其他一些子句会有所帮助。把所有这些 if 放到一个大的 if/else if/else 循环中:

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

你可能会得到一个你意想不到的角色,比如回车。

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

最新更新