来源:点击打开链接
还是A+B,难点是会拼写英文(囧)和处理字符串。转换字符串和数字可以采用map的方程。
简要用法:map<T1(数据类型),T2(数据类型)> name(名称)
定义:可以直接使用下标name[T1的内容]来访问T2,如果T2是INT或char型的话还可以自加。。详情请见STL相关。。
#include <iostream>
#include <map>
#include <stdlib.h>
#include <string>
using namespace std;
map<string,char> tw;
void initmap()
{
tw["zero"]='0';
tw["one"]='1';
tw["two"]='2';
tw["three"]='3';
tw["four"]='4';
tw["five"]='5';
tw["six"]='6';
tw["seven"]='7';
tw["eight"]='8';
tw["nine"]='9';
}
int main()
{
string tar;
initmap();
while(getline(cin,tar))
{
int n1,n2;
string c1,c2;
int firstl=tar.find('+',0);
int secondl=tar.find('=',0);
int startpos=0;
int endpos=0;
for(int i=0;i<firstl;i++)
{
string tmp;
if(tar[i]==' ')
{
endpos=i-1;
for(int j=startpos;j<=endpos;j++)
tmp+=tar[j];
startpos=endpos+2;
c1+=tw[tmp];
}
}
startpos+=2;//挪到加号后边
for(int k=firstl+2;k<secondl;k++)
{
string tmp2;
if(tar[k]==' ')
{
endpos=k-1;
for(int p=startpos;p<=endpos;p++)
tmp2+=tar[p];
startpos=endpos+2;
c2+=tw[tmp2];
}
}
n1=atoi(c1.c_str());
n2=atoi(c2.c_str());
if(n1==0 && n2==0)
break;
else
{
cout<<n1+n2<<endl;
}
}
return 0;
}
本文介绍了一种利用C++中的map容器实现将英文描述的数字字符串转换为实际数值的方法,并通过具体示例展示了如何解析这类字符串并进行数学运算。
656

被折叠的 条评论
为什么被折叠?



