首页 > 代码库 > 阿拉伯数换成英文

阿拉伯数换成英文

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <set>
#include <algorithm>
#include <string>
#include <sstream>
 using namespace std;
 string num1[]={"","thousand","million","billion"};
 string num2[] = { "","","twenty","thirty","forty","fifty","sixty","seventy",
	 "eighty","ninety" };
 string num3[] = { "zero", "one", "two", "three", "four", "five", "six",
	 "seven", "eight", "nine" };
 string num4[] = { "ten", "eleven","twelve","thirteen","fourteen","fifteen",
	 "sixteen","seventeen","eighteen","nighteen" };

 string parse(long num)
 {
     string res;
	 if(num>=0&&num<=9) res+=num3[num];
	 else if(num>=10&&num<=19) res+=num4[num%10];
	 else if(num>=20&&num<=99) 
	 {
		 res+=num2[num/10];
		 if(num%10==0) return res;
		 res+=" ";
		 res+=num3[num%10];
	 }
	 else
	 {
		 res+=num3[num/100];
		 res+=" hundred";
		 num%=100;
		 if(num)
		 {
			 res+=" and ";
			 res+=parse(num);
		 }
	 }
	 return res;
 }
 int main()
 {
	 long num;
	 while(cin>>num)
	 {
		vector<int> parts;
		string res;
	     if(num==0)
		 {
			 cout<<"zero"<<endl;
			 continue;
		 }
		 else if(num>999999999||num<0)
		 {
			 cout<<"error"<<endl;
			 continue;
		 }
		 while(num)
		 {
			 int tmp=num%1000;
			 parts.push_back(tmp);
			 num/=1000;
		 }
		 for(int i=parts.size()-1;i>=0;--i)
		 {
			 string tmp=parse(parts[i]);
			 if(tmp=="")continue;
			 res+=tmp;
			 if(i)
			 {
				 res+=" ";
				 res+=num1[i];
				 res+=" ";
			 }

		 }
		 while (res[res.size()-1]==‘ ‘) res.erase(res.end()-1);
		 cout<<res<<endl;
	 }
	 system("pause");
	 return 0;
 }

  

阿拉伯数换成英文