2014-02-22 71 views
-4

此程序正在工作,但只能用数字。我需要它来处理字符串。我不知道如何做到这一点。没有任何工作。我在寻求一些帮助。堆栈c中的字符串

#include <stdio.h> 
#include <conio.h> 
#define MAXSIZE 20 

struct stack    
{ 
    int stk[MAXSIZE]; 
    int top; 
}; 

typedef struct stack STACK; 
STACK s; 

void push (void); 
void display (void); 

void main() 
{ 
    int choice; 
    int option = 1; 
    s.top = -1; 

    while (option) 
    { 
     printf ("\nNacisnij 1 aby wprowadzic elemnt do stosu\n"); //press 1 to push on stack 
     printf ("Nacisnij 2 aby wyswietlic stan stosu\n"); //press 2 to display stack 
     printf ("Nacisnij 3 aby zakonczyc\n\n"); //press 3 to exit 
     scanf("%d", &choice); 

     switch (choice) 
     { 
      case 1: 
       push(); 
       break; 
      case 2: 
       display(); 
       break; 
      case 3: 
       return; 
     } 
     fflush (stdin); 
    } 
} 

void push() 
{ 
    int num; 
    if (s.top == (MAXSIZE - 1)) 
    { 
     printf ("Stos jest pelen\n");// stack is full 
     return; 
    } 
    else 
    { 
     printf ("\nWprowadz element\n");// enter element 
     scanf("%d", &num); 
     s.top = s.top + 1; 
     s.stk[s.top] = num; 
    } 
    return; 
} 

void display() 
{ 
    int i; 
    if (s.top == -1) 
    { 
     printf ("Stos jest pusty\n"); //stack is empty 
     return; 
    } 
    else 
    { 
     printf ("\nStan stosu\n"); //state of the stack 
     for (i = s.top; i >= 0; i--) 
     { 
      printf ("%d\n", s.stk[i]); 
     } 
    } 
    printf ("\n"); 
} 
+1

请打算您的代码,并给我们一个实际的问题。 – deviantfan

回答

1

您需要定义int stk[MAXSIZE];作为一个字符数组,使之成为字符串的工作,你需要改变这一行读取一个字符串scanf ("%d", &num);所以,你需要的是

struct stack    
{ 
    char stk[MAXSIZE][MAX_STR_LEN];// You have to define MAX_STR_LEN to a value you desire 
    int top; 
}; 

更改后的变化代码

scanf ("%d", &num); 
s.top = s.top + 1; 
s.stk[s.top] = num; 

s.top = s.top + 1; 
scanf ("%s", s.stk[s.top]);