7-3 符号配对 (20分) 请编写程序检查C语言源程序中下列符号是否配对:/与/、(与)、[与]、{与}。
输入格式: 输入为一个C语言源程序。当读到某一行中只有一个句点.和一个回车的时候,标志着输入结束。程序中需要检查配对的符号不超过100个。
输出格式: 首先,如果所有符号配对正确,则在第一行中输出YES,否则输出NO。然后在第二行中指出第一个不配对的符号:如果缺少左符号,则输出?-右符号;如果缺少右符号,则输出左符号-?。
输入样例1: void test() { int i, A[10]; for (i=0; i<10; i++) /*/ A[i] = i; } .
输出样例1: NO /*-? 输入样例2: void test() { int i, A[10]; for (i=0; i<10; i++) /**/ A[i] = i; }] .
输出样例2: NO ?-] 输入样例3: void test() { int i double A[10]; for (i=0; i<10; i++) /**/ A[i] = 0.1*i; } .
输出样例3: YES
#include <bits/stdc++.h> using namespace std; stack<char> s; void print(char ch) { if (ch == '(') printf("(-?\n"); else if (ch == '[') printf("[-?\n"); else if (ch == '{') printf("{-?\n"); else if (ch == '<') printf("/*-?\n"); } int main() { char dangqian; char shangyige; int flag = 1; for (;;) { shangyige = dangqian; dangqian = getchar(); if (dangqian == '\n') { if (shangyige == '.') break; } if (dangqian == '*') { if (shangyige == '/') { s.push('/'); s.push('*'); dangqian = 'a'; } } else if (dangqian == '(' || dangqian == '[' || dangqian == '{') { s.push(dangqian); } if (dangqian == ')') { if (s.empty() == false && s.top() == '(') { s.pop(); } else { printf("NO\n"); flag = 0; if (s.empty() == true) { printf("?-)\n"); } break; } } if (dangqian == ']') //test123 { if (s.empty() == false && s.top() == '[') { s.pop(); } else { printf("NO\n"); flag = 0; if (s.empty() == true) { printf("?-]\n"); } break; } } if (dangqian == '}') { if (s.empty() == false && s.top() == '{') { s.pop(); } else { printf("NO\n"); flag = 0; if (s.empty() == true) { printf("?-}\n"); } break; } } if (dangqian == '/' && shangyige == '*') { dangqian = 'a'; if (s.empty() == false && s.top() == '*') { s.pop(); s.pop(); } else { printf("NO\n"); flag = 0; if (s.empty() == true) { printf("?-*/\n"); } break; } } } if (flag == 1 && s.empty() == true) printf("YES\n"); else if (flag == 1 && s.empty() == false) { printf("NO\n"); print(s.top()); } else if(flag == 0&&s.empty() == false){ print(s.top()); } }还有点问题 https://blog.csdn.net/qq_44378358/article/details/106909513 这一个,它输出的是没有配对的从左往右数第一个。也对了 参考 https://blog.csdn.net/rAiNFalLzZ/article/details/107781328?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param https://blog.csdn.net/qq_41611106/article/details/82590671?utm_medium=distribute.pc_relevant.none-task-blog-title-7&spm=1001.2101.3001.4242 https://blog.csdn.net/weixin_44996854/article/details/102752241?utm_medium=distribute.pc_relevant.none-task-blog-title-2&spm=1001.2101.3001.4242