此程序正在运行,但仅限于数字。我需要它来处理字符串。我不知道该怎么做。什么都行不通。我正在寻求帮助。
#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");
}
答案 0 :(得分: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]);