本帖最后由 fanxing 于 2015-6-15 20:21 编辑
/*
gcc -o test test .c
如果没有提示错误的话
./test就可以运行
测试数据:
a+(b*(c-d^e)+f)/m
a+(b*(c-d^e)+f/m
a+(b*(c-d^e+f/m)/m
a+(b*(#c-d^e)+f)/m
*/
#include <stdio.h>
#include <iostream>
#include <deque>
using namespace std;
#define Max 100
char str[Max], exp[Max], stack1[Max], ch;
int i = 0, j = 0, t = 0, top = 0, errorblog = 0;
deque <int> pipei;
void start(){
i = 0, j = 0, t = 0, top = 0;
printf("************************ Expression to NBL form ************************\n\n");
printf("Please input the expression: ");
scanf("%s", str);
ch = str;
i++;
}
void end(){
while(top != 0){
exp[t] = stack1[top];
t++;
top--;
}
printf("\nNBL form:------------------- ");
for(j = 0; j < t; j++) printf("%c", exp[j]);
printf("\n\n#####################################################################\n\n");
}
void error(char index){
while(1){
if (index == 'z') {
for(int z = 0; z < 1; z++){
printf(" ");
for(int x = 0; x < i - 1; x++) printf(" ");
printf("^\n");
}
printf("Error: ^所指字符为不可识别字符\n\n\n");
}
if (index == 'k'){
printf(" ");
for(int x = 0; x < strlen(str); x++){
if(pipei.front() == x) {
printf("^");
pipei.pop_front();
}
else printf(" ");
}
printf("\n\n");
printf("Error: ^所指括号为孤独的括号\n\n");
while(!pipei.empty()){
pipei.pop_front();
}
}
errorblog = 1;
break;
}
//exit(0);
}
int main(){
while(1){
start();
while(ch != '\0'){
if((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')){
exp[t] = ch;
t++;
}
else if(ch == '('){
top++;
stack1[top] = ch;
pipei.push_back(i - 1);
}
else if(ch == ')'){
while(stack1[top] != '('){
exp[t] = stack1[top];
top--;
t++;
}
top--;
if(str[pipei.back()] == '(') pipei.pop_back();
else pipei.push_back(i - 1);
}
else if(ch=='+' || ch=='-'){
while(top != 0 && stack1[top] != '('){
exp[t] = stack1[top];
top--;
t++;
}
top++;
stack1[top] = ch;
}
else if(ch == '^'){
while(stack1[top] == '^'){
exp[t] = stack1[top];
top--;
t++;
}
top++;
stack1[top] = ch;
}
else if(ch == '*' || ch == '/'){
while(stack1[top] == '*' || stack1[top] == '/'){
exp[t] = stack1[top];
top--;
t++;
}
top++;
stack1[top] = ch;
}
else error('z');
ch = str;
i++;
}
if(!pipei.empty()) error('k');
if(errorblog != 1) end();
}
return 0;
}
第三组的正确结果应为:
************************ Expression to NBL form ************************
Please input the expression: a+(b*(c-d^e+f/m)/m ^
Error: ^所指括号为孤独的括号
|