括号平衡器程序

时间:2016-09-29 17:05:13

标签: c

我通过堆栈制作了一个括号检查程序。其中它将字符串作为输入,并将检查字符串或表达式是否具有相等的否。打开和关闭括号。如果是,它将打印" Paranthesis是平衡的"。否则" Paranthesis不平衡"。但另一个是非常奇怪的是它只打印一些随机值并且没有将表达式作为输入,只是打印一些垃圾值本身。这是代码

#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;
}

并输出: - enter image description here

2 个答案:

答案 0 :(得分:3)

它打印随机数据的原因是因为您打印expression而没有在其中写入任何内容:

printf("%s", &expression);

所以你实际上并没有阅读任何内容。你需要使用scanf

scanf("%s", expression);

答案 1 :(得分:1)

所以我们声明一个char数组:

char expression[100];

然后我们打印出来:

printf("%s", &expression);

除了这个空的char数组真的不是空的,而是包含它占用的内存中存在的任何垃圾数据。因此,您最多可以打印100个随机字符。

您是否想在此处使用scanf

相关问题