fork download
  1. #include <stdio.h>
  2.  
  3. #define SIZE 5
  4. int stack[SIZE];
  5. int sp;
  6.  
  7. void push(int value);
  8. int pop(void);
  9.  
  10. int main(void)
  11. {
  12. int resp, data;
  13. int i;
  14.  
  15. sp = 0;
  16.  
  17. while(1){
  18. printf("1: push 2:pop 0:end : ");
  19.  
  20. /* 【修正】数字が正しく入力されなかったらループを抜ける安全装置 */
  21. if (scanf("%d", &resp) != 1) {
  22. printf("\n不正な入力、または入力が終了しました。\n");
  23. break;
  24. }
  25.  
  26. if(!resp) break;
  27.  
  28. switch(resp){
  29. case 1:
  30. printf("push : ");
  31. if (scanf("%d", &data) != 1) break;
  32. push( data );
  33. break;
  34. case 2:
  35. pop();
  36. break;
  37. }
  38. printf("sp=%d\n", sp);
  39. }
  40. printf("\n");
  41.  
  42. for(i=0; i<sp; i++){
  43. printf("stack[%d]=%d\n", i, stack[i]);
  44. }
  45.  
  46. return 0;
  47. }
  48.  
  49. void push(int value)
  50. {
  51. if(sp >= SIZE){
  52. printf("スタックが満杯で入りませんでした\n");
  53. }else{
  54. stack[sp++] = value;
  55. }
  56. }
  57.  
  58. int pop(void)
  59. {
  60. if(sp <= 0){
  61. printf("スタックが空で取り出せませんでした\n");
  62. return 0;
  63. }else{
  64. return stack[--sp];
  65. }
  66. }
  67.  
Success #stdin #stdout 0s 5320KB
stdin
1
10
0
stdout
1: push 2:pop 0:end : 
不正な入力、または入力が終了しました。