括号检查器在 c 中使用数组堆栈,每次都不产生正确的输出



我试图使用数组堆栈在 c 中编写一个括号检查器。代码不会给出错误消息,但有时会给出正确的输出,有时会给出错误的输出。 我将不胜感激如何改进代码或任何其他建议。我是一名初学者C程序员。 我试图将输入作为字符串,但无法做到。有什么建议吗?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 25
int top = -1;
char stack[MAX];
void push(char x)
{
if(top == MAX - 1){
printf("Stack Overflown");
return;
}
stack[++top] = x;
}
char pop()
{
char popped;
if(top == -1) {
printf("Stack Underflown");
return 0;
}
popped = stack[top];
--top;
return popped;
}
char Top()
{
return (stack[top]);
}
int arePair(char opening,char closing)
{
if(opening =='(' && closing == ')') return 1;
else if((opening =='{' && closing == '}')) return 1;
else if (opening =='[' && closing == ']') return 1;
return 0;
}
int paranthesesBalanced(char *exp,int size)
{
for (int i=0;i<size;i++)
{
if(exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
push(exp[i]);
else if (exp[i] == ')' || exp[i] == '}'|| exp[i] == ']') 
{
if(top == -1 || !arePair(Top(),exp[i]))
return 0;
else
pop();
}
}
return (top == -1 ? 1:0);
}

int main()
{
char exp[25];
int size=0;
printf("Enter the size of 
expressionn");
scanf("%d",&size);
printf("Enter the expression(Less than 
25 characters): n");
//scanf("%[ˆn]%",exp);
for (int i=0;i<size;i++)
{
scanf("%c",&exp[i]);
}
if(paranthesesBalanced(exp,size))
printf("Balanced!n");
else
printf("Not Balanced!n");
}

我同意上面的评论,你应该花一些时间来学习如何调试你的程序。

代码的问题在于读取用户输入的方式。 %c 匹配所有字符,包括换行符。当前形式的代码在用户数据大小和数据本身之间读取换行符作为输入的第一个字符,因此 exp[0] == ''。有多种方法可以解决此问题,例如刷新输入或取消注释您注释的行(并摆脱多余的百分号或切换到其他读取输入的方式,例如使用 %s 而不是在循环中使用 %c。

希望对您有所帮助。

这是正常工作的最小修改版本:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 25
int top = -1;
char stack[MAX];
void push(char x)
{
if(top > MAX - 1){              //CHANGED
printf("Stack Overflown");
return;
}
stack[++top] = x;
}
char pop()
{
char popped;
if(top == -1) {
printf("Stack Underflown");
return 0;
}
popped = stack[top];
--top;
return popped;
}
char Top()
{
return (stack[top]);
}
int arePair(char opening,char closing)
{
if(opening =='(' && closing == ')') return 1;
else if((opening =='{' && closing == '}')) return 1;
else if (opening =='[' && closing == ']') return 1;
return 0;
}
int paranthesesBalanced(char *exp,int size)
{
for (int i=0;i<size;i++)
{
if(exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
push(exp[i]);
else if (exp[i] == ')' || exp[i] == '}'|| exp[i] == ']') 
{
if(top == -1 || !arePair(Top(),exp[i]))
return 0;
else
pop();
}
}
return (top == -1 ? 1:0);
}

int main()
{
char exp[25];
int size=0;
printf("Enter the size of xpressionn");
scanf(" %d",&size);
printf("Enter the expression(Less than 25 characters): n");
scanf("%s",exp);     //DELETED FOR LOOP - BETTER USE GETCHAR() RATHER THAN SCANF
printf("%sn",exp);
if(paranthesesBalanced(exp,size))
printf("Balanced!n");
else
printf("Not Balanced!n");
}

而不是scanf你可以这样做,因为scanf不支持空格,即如果你输入hello world它只会读取hello。另类:

int i,count++;
while((i=getchar())!=EOF)
{
if((i!=')&&(count<MAX))
exp[count++]=i;
else
break;
}

通过这种方式,您可以轻松检查表达式的长度及其限制+它将允许您输入空格。

最新更新