我通过堆栈制作了一个括号检查程序。其中它将以字符串作为输入,并检查字符串或表达式是否具有相等的编号。左大括号和右大括号。如果是,它将打印“括号平衡”。否则“括号不平衡”。但另一个很奇怪,它只是打印一些随机值,并且不将表达式作为输入,只是自己打印一些垃圾值。这是代码
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
// Structure defining Stack data structure
struct Stack {
int count;
char data[50];
} s;
/*
Initializes the count index to 0
*/
void initialize() {
s.count = 0;
}
/*
Checks if Stack is Full or not
*/
bool Is_Full() {
if(s.count > 50)
return true;
else
return false;
}
/*
Checks if Stack is Empty or not
*/
bool Is_Empty() {
if(s.count == 0){
return true;
}
else{
return false;
}
}
/*
Adds an element to stack and then increment count index
*/
bool push(int num) {
if (Is_Full())
return false;
else {
s.data[s.count + 1] = num;
s.count++;
return true;
}
}
/*
Removes count element from stack and decrement count index
*/
bool pop() {
if (Is_Empty())
return false;
else {
s.count = s.count - 1;
s.data[s.count+1];
}
return true;
}
int main(void) {
char expression[100];
int i, len;
initialize();
printf("Enter an expression \n");
printf("%s", &expression);
len = strlen(expression);
/*
# for '{' : we push '{' in stack
# for '}' : we pop a character from stack. For every '}' there must be one '{' earlier.
This will ensure that
** There are equal number of '{' and '}' characters in string.
** For every '{' there is a '}' in input string later.
*/
for(i = 0; i < len; i++){
if(expression[i] == '(' || expression[i] == '{' || expression[i] == '['){
push(expression[i]);
}
if(expression[i] == ')' || expression[i] == '}' || expression[i] == ']'){
pop();
}
}
if(Is_Empty()){
printf("Parenthesis are balanced\n");
}
else{
printf("Parenthesis are unbalanced\n");
}
return 0;
}
and here's the output:-
它打印随机数据的原因是因为你正在打印expression
不写入任何内容:
printf("%s", &expression);
所以你实际上并没有读任何内容。你需要使用scanf
为了那个原因:
scanf("%s", expression);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)