2014-10-10 99 views
-2
#include <stdio.h> 

#define MAXSIZE 101 

int A[MAXSIZE]; 
int top=-1; 
    int data; 
void push() 
{ 

    printf("Enter a number\n"); 
    scanf(" %d",&data); 

    if (top==MAXSIZE-1){ 
     printf("Overflow.Array size limit reached\n"); 
     return; 
    } 
    A[++top]=data; 
} 

void pop() 
{ 
    if(top==-1){ 
     printf("Empty Stack!\n"); 
     return; 
    } 
    top--; 
} 

int isEmpty() 
{ 
    if(top==-1) 
    { 
     printf("Empty yes\n"); 
     return 0; 
    } 

} 

int first() 
{ 
    return A[top]; 
} 

int printStack() 
{ 
    int i=0; 
    for(i=0;i<=top;i++) 
    { 
     printf("%d \n",A[i]); 
    } 
    return 0; 
} 


int main(int argc, char const *argv[]) 
{ 
    int choice; 
    int flag=1; 

    do{ 
     printf("The options are\n"); 
     printf("1\t\t Push\n2\t\t Pop\n3\t\t Empty\n4\t\t Top\n5\t\t Print\n\n"); 

     scanf(" Enter choice %d",&choice); 
     switch(choice) 
    { 
     case 1: 
      push(); 
      break; 
     case 2: 
      pop(); 
      break; 
     case 3: 
      isEmpty(); 
      break; 
     case 4: 
      first(); 
      break; 
     case 5: 
      printStack(); 
      break; 
     default: 
      printf("Please enter correct menu choice"); 

    } 

    printf("Wanna repeat again ? Press 1 to repeat 0 to exit\n"); 
    scanf("%d",&flag); 


    }while(flag); 

    return 0; 
} 

我試過使用數組創建堆棧的實現。我在循環中遇到了一些問題。該程序運行,它要求選擇,並從開關盒驅動菜單它應該去那個功能,執行它,並返回到主()C中堆棧的數組實現

但有一些問題,它啓動循環再次沒有執行任何功能

+1

請學習如何調試你的程序:使用一個調試器或者簡單地將'printf'放在這裏和那裏來觀察行爲或你的程序。閱讀SO的幫助文字。 – 2014-10-10 16:45:18

+1

你怎麼知道它沒有執行任何功能? – Degustaf 2014-10-10 16:46:16

回答

0
scanf(" Enter choice %d",&choice); 

是不是在寫一個scanf()功能的有效途徑。要在屏幕上顯示消息,我們有puts()printf(),但scanf()僅用於獲取輸入。異常行爲在這裏解釋:

scanf() reference

做你展示一個消息到屏幕,然後採取從用戶輸入的任務,重寫語句:

printf("Enter your choice "); 
scanf("%d", &choice); 
0

更改您的scanf聲明:

printf("Enter your choice :"); 
scanf("%d", &choice); 
+0

好的,但也許你可以解釋*爲什麼*。 – Caleb 2014-10-10 20:14:21

+0

由於scanf從控制檯讀取,它不會打印到控制檯。 – 2014-10-10 20:16:32

+0

@Caleb要打印到控制檯我們使用printf() – 2014-10-10 20:18:35