C++语言表达式求值

#include <stack>            //引入了C++标准模板库的stack #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; void Match() { 	char test[100];    //定义了一个char类型的test数组装“{{([])}}”这样的字符串,用以测试 	cin >> test;       //输入字符串 	stack<char>S;      //定义一个栈,类型是char类型 	bool ismatch = true;    //定义一个bool类型的变量,先赋值为true,如果在循环体中发现是不匹配的,就把值变成false 	for (int i = 0; test[i] != '\0'; i++) {             //for循环对数组每个元素都进行测试,如果是'[','{','('就放入栈         //如果是']','}',')',就取出栈顶元素,与当前元素进行匹配,一旦发现不匹配,ismatch就变成                         //false 		switch (test[i]) 		{ 		case '[': 		case '{': 		case '(': { 			S.push(test[i]); 			break; 		} 		case ']': { 			char temp = S.top(); 			S.pop();            //取栈顶元素,并弹栈 			if (temp != '[') { 				ismatch = false; 			} 			break; 		} 		case '}': { 			char temp = S.top(); 			S.pop();            //取栈顶元素,并弹栈 			if (temp != '{') { 				ismatch = false; 			} 			break; 		} 		case ')': { 			char temp = S.top(); 			S.pop();            //取栈顶元素,并弹栈 			if (temp != '(') { 				ismatch = false; 			} 			break; 		} 		default: 			break; 		} 		if (ismatch == false) {    //如果ismatch是false,就终止循环,并且打印不匹配 			printf("\n%s括号不匹配\n", test); 			break; 		} 	} 	if (ismatch == true) { 		printf("\n%s括号是匹配的\n", test); 	}  } int main() { 	//测试数据:{([({{([[[{{}}]]])}})])} 	Match(); }

第一次写文章