POJ2121 Inglish-Number Translator

本文介绍了一种使用C++将英文描述的数字转换为整数的方法。通过构建映射表来对应英文单词与数值,并利用标准库函数进行字符串处理,实现了从简单数字到百万级别的数字描述的有效转换。
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->#include<iostream>
#include
<string>
#include
<map>
#include
<algorithm>
usingnamespacestd;

map
<string,int>mapTable;

voidinitMapTable()
{
mapTable[
"zero"]=0;
mapTable[
"one"]=1;
mapTable[
"two"]=2;
mapTable[
"three"]=3;
mapTable[
"four"]=4;
mapTable[
"five"]=5;
mapTable[
"six"]=6;
mapTable[
"seven"]=7;
mapTable[
"eight"]=8;
mapTable[
"nine"]=9;
mapTable[
"ten"]=10;
mapTable[
"eleven"]=11;
mapTable[
"twelve"]=12;
mapTable[
"thirteen"]=13;
mapTable[
"fourteen"]=14;
mapTable[
"fifteen"]=15;
mapTable[
"sixteen"]=16;
mapTable[
"seventeen"]=17;
mapTable[
"eighteen"]=18;
mapTable[
"nineteen"]=19;
mapTable[
"twenty"]=20;
mapTable[
"thirty"]=30;
mapTable[
"forty"]=40;
mapTable[
"fifty"]=50;
mapTable[
"sixty"]=60;
mapTable[
"seventy"]=70;
mapTable[
"eighty"]=80;
mapTable[
"hundred"]=100;
mapTable[
"thousand"]=1000;
mapTable[
"million"]=1000000;
}
voidsolve(string&str)
{
string::size_typepos=str.find_first_of('');
if(pos==string::npos)
{
//只有一个单词
if(str=="negative")
{
cout
<<"-0"<<endl;
}
elseif(mapTable.find(str)!=mapTable.end())
{
cout
<<mapTable[str]<<endl;

}
}
else
{
//至少个单词
stringinput=str;
intsum=0,msum=0,tsum=0,hsum=0;
boolbMinus=false;
intcount=0;
string::iteratorstart=input.begin();
string::iteratorend=input.end();
do
{
stringword;
end
=find(start,input.end(),'');//找到分隔符
copy(start,end,back_inserter(word));
++count;//单词计数
if(word=="negative")
{
bMinus
=true;
}
else
{
if(count==2&&word=="zero")
{
bMinus
=false;
}
intcurNum=mapTable[word];
if(curNum==100)
{
hsum
=sum*100;
sum
=0;
}
elseif(curNum==1000)
{
tsum
=(hsum+sum)*1000;
hsum
=0;
sum
=0;
}
elseif(curNum==1000000)
{
msum
=(tsum+hsum+sum)*1000000;
tsum
=0;
hsum
=0;
sum
=0;
}
else
{
sum
+=curNum;
}
}
if(end==input.end())
{
if(bMinus)
cout
<<"-";
cout
<<msum+tsum+hsum+sum<<endl;
break;
}
start
=++end;
}
while(end!=input.end());
}
}
intmain()
{
stringstr;
initMapTable();
while(getline(cin,str))
{
if(str.length()==0||str.length()==1)
continue;
solve(str);
}
return0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值