切分表达式-----写个 tokenizer 吧

在这里插入图片描述在这里插入图片描述
一开始忽略了区分负号与减号,未通过!:

#include<iostream>
#include<cstring>
using namespace std;
int main(){
    
    
	char a[50];
	cin>>a;
	for(int i=0;i<strlen(a)-1;i++){
    
    
		cout<<a[i];
		if(a[i]>='0' && a[i]<='9' && a[i+1]>='0' && a[i+1]<='9');
		else cout<<endl;
	}
	cout<<a[strlen(a)-1];
	return 0;
}

下面修改,其实不只要区分负号与减号!!!调试过程中发现,细节好多呀,我给出下面的测试样例:

-(-1.1+6*5)/(0.233+6+(-5))-1.1+(+5.33)

正确的输出为:

-
(
-1.1
+
6
*
5
)
/
(
0.233
+
6
+
(
-5
)
)
-
1.1
+
(
+5.33
)

如果不是这样,比较一下自己的输出与它差在哪里,然后对代码对症下药就好了,AC:

#include<iostream>
#include<cstring>
using namespace std;
int main(){
    
    
	char a[50];
	cin>>a;
	for(int i=0;i<strlen(a)-1;i++){
    
    
		cout<<a[i];
		if(a[i]>='0' && a[i]<='9' && a[i+1]>='0' && a[i+1]<='9');
		else if(a[i]>='0' && a[i]<='9' && a[i+1]=='.');
		else if(a[i]=='.');
		else if(a[i]=='-' && i==0 && a[i+1]>='0' && a[i+1]<='9');
		else if(a[i]=='-' && i>0 && a[i+1]>='0' && a[i+1]<='9' && a[i-1]=='(');
		else if(a[i]=='+' && i==0 && a[i+1]>='0' && a[i+1]<='9');
		else if(a[i]=='+' && i>0 && a[i+1]>='0' && a[i+1]<='9' && a[i-1]=='(');
		else cout<<endl;
	}
	cout<<a[strlen(a)-1];
	return 0;
}

猜你喜欢

转载自blog.csdn.net/interestingddd/article/details/114992933