```c
#include<stdio.h>
#define MAXLEN 100
typedef int DataType;
int Menu() {
printf("\n顺序栈的各种操作\n");
printf("===============\n");
printf("| 1--初始化 |\n");
printf("| 2--入栈操作 |\n");
printf("| 3--出栈操作 |\n");
printf("| 4-求栈顶元素|\n");
printf("| 0--返回 |\n");
printf("===============\n");
printf("请输入(0-4)\n");
return 1;
}
typedef struct {
DataType date[MAXLEN];
int top;
}SeqStack;
void IniStack(SeqStack* S)
{
S->top = -1;
}
int EmptyStack(SeqStack* S) {
if (S->top == -1)
return 1;
else
return 0;
}
int FullStack(SeqStack* S) {
if (S->top == MAXLEN - 1)
return 1;
else
return 0;
}
int PashStack(SeqStack* S, DataType x) {
if (FullStack(S))
{
printf("Full cant paush !");
return 0;
}
else {
S->top++;
S->date[S->top] = x;
return 1;
}
}
int pop(SeqStack* S, DataType* x) {
if (EmptyStack(S)) {
printf("EmptyStack can't pop");
return 0;
}
else {
*x = S->date[S->top];
S->top--;
return 1;
}
}
int GetTop(SeqStack* S, DataType* x) {
if (EmptyStack(S)) {
printf("EmptyStack can'GetTop");
return 0;
}
else {
*x = S->date[S->top];
}
}
void main() {
int i, n, flag;
SeqStack S;
DataType x;
char ch1, ch2, a;
ch1 = 'y';
while (ch1 == 'Y' || ch1 == 'y') {
Menu();
scanf_s("%c",&ch2);
getchar();
switch (ch2) {
case '0':
break;
case '1':
IniStack(&S);
printf("IniStack sucess!");
break;
case '2':
printf("请输入入栈的个数:");
scanf_s("%d", &n);
printf("请输入%d个入栈的整数",n);
for ( i = 0; i < n;i++) {
scanf_s("%d",&x);
flag = PashStack(&S, x);
if (flag == 1)
printf("入栈成功!");
}
break;
case '3':
printf("请输入要出栈的元数个数:");
scanf_s("%d",&n);
printf("出栈的元数个数为%d",n);
for ( i = 0; i < n;i++) {
flag=pop(&S,&x);
printf("%d",x);
}
if (flag == 1) {
printf("出栈成功!");
}
else {
printf("出栈失败!");
}
break;
case '4':
if (flag ==GetTop(&S, &x)) {
printf("当前栈顶元素为:%d",x);
break;
}
default:
printf("输入元素有误请在0-4之间选择!");
}
if (ch2 == '0') {
printf("\n按回车键继续,按任意键返回主菜单");
scanf_s("%c",&a);
if (a != '\xA') {
ch1 = 'stop';
}
}
}
}
执行1,2后执行不了3,直接default求解
因为case '2'中scanf_s("%d",&n)时用户输入了数值和换行符‘\n’,在读取了数值之后,输入缓存里就残留了一个‘\n’。
再次使用scanf_s("%c")会读取输入缓存里上次残留的‘\n’,而不是读取新输入的字符。这样就造成了严重的错误。
可以在用 scanf_s("%c",&ch2); 读取字符前用 setbuf(stdin, NULL); 清除输入缓存。
setbuf(stdin, NULL);
scanf_s("%c",&ch2);
或者用 scanf("%1s",&ch2); 读取字符,用"%1s"会跳过空格与换行符,读取一个非空格与换行符的字符。
如有帮助,望采纳!谢谢! 点击我这个回答右上方的【采纳】按钮
scanf_s("%c",&ch2,1);
另外你case '2'的处理中有scanf_s("%d",&n)的输入,输入结束的换行符还在输入缓存里,会被scanf_s("%c"接收,所以输入'3'不起作用
最好在scanf_s("%d",&n)后面都加一句getchar();
用的Visual Studio 2019