使用数组的堆栈实现,但在交换机情况下有错误 [英] Stack implementation using array but in switch case there is error

查看:68
本文介绍了使用数组的堆栈实现,但在交换机情况下有错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

while(1)
 {
  printf("Select and enter your choice:\n");
  printf("(1)PUSH\n");
  printf("(2)POP\n");
  printf("(3)Display\n");
  scanf("%d",&ch);
  switch(ch)
  {
   case 1:
    printf("Enter the element:");
    scanf("%d",&x);
    push(stack,x);
    break;
   case 2:
    pop(stack);
    break;
   case 3:
    display(stack);
    break;
   case 4:
    return 0;    
  }
 }

推荐答案

我首先使用调试器,然后看看究竟是什么在 ch 中,当你执行scanf时:很可能ch被定义为char值,并且你试图将一个整数放入其中 - 所以你得到的是什么不是你所期望的!



我不使用%d - 我使用%c并与1,2进行比较和'3'代替。
I'd start by using the debugger, and looking at exactly what go put in ch when you did the scanf: chances are that "ch" is defined as a char value, and you are trying to put an integer into it - so what you get out is not what you expected!

I'd not use "%d" - I'd use "%c" and compare with '1', '2', and '3' instead.


ch 应声明 int

但是,即使 ch (错误地)声明 char ,那开关 可以工作。

观察到的不当行为是什么?
ch should be declared int.
However, even if ch is (by mistake) declared char, that switch could work.
What's the observed misbehaviour?


这篇关于使用数组的堆栈实现,但在交换机情况下有错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆