괄호가 들어간 문장을 입력하고 괄호가 올바르게 표현되었을 때와 틀렸을 때를 표현하는 프로그램 만들기

주의: 띄어쓰기 들어간 문자열의 입력? fgets함수사용하기 (gets함수는 비표준함수라 사용X)



코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#pragma warning(disable:4996)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define max 100
typedef struct
{
    char data[max];
    int top;
}stackType;
 
int check(char* exp);
void init(stackType* s);
void push(stackType* s, int x);
int pop(stackType* s);
int is_full(stackType* s);
int is_empty(stackType* s);
int main()
{
    stackType s;
    char exp[20];
    fgets(exp, sizeof(exp), stdin);
    if (check(exp) == 1)
        puts("성공!");
    else
        puts("실패!");
    return 0;
}
void init(stackType* s)
{
    s->top = -1;
}
int is_full(stackType* s)
{
    return s->top == max - 1;
}
int is_empty(stackType* s)
{
    return s->top == -1;
}
void push(stackType* s, int x)
{
    if (is_full(s))
    {
        fprintf(stderr, "원소가 다 찼습니다.\n");
        return;
    }
    s->data[++(s->top)] = x;
}
int pop(stackType* s)
{
    if (is_empty(s))
    {
        fprintf(stderr, "원소가 없습니다\n");
        exit(1);
    }
    return s->data[(s->top)--];
}
int check(char* exp)
{
    stackType s;
    char ch, open_ch;
    int n = strlen(exp);
    init(&s);
    for (int i = 0; i < n; i++)
    {
        ch = exp[i];
        switch (ch)
        {
        case '(':case '[':case'{':
            push(&s, ch);
            break;
        case ')':case']':case'}':
            if (is_empty(&s))return 0;
            else
            {
                open_ch = pop(&s);
                if ((open_ch == '(' && ch != ')'|| (open_ch == '{' && ch != '}'||
                    (open_ch == '[' && ch != ']'))
                    return 0;
                
            }
            break;
        }
    }
    //괄호검사 다했는데 스택에 원소가 남아있다면? => 잘못된 수식
    if (!is_empty(&s))return 0;
    return 1;
}
cs


결과





+ Recent posts