大家在编写涉及到金额的程序的时候,有时候需要将小写的人民币金额转换成大写表示
下面的代码介绍了转换的实现过程,大家可以参考一下!
#pragma warning(disable:4786)
#include <string>
#include <stdio.h>
#include <iostream>
#include <vector>
using std::vector;
using std::string;
using std::cout;
using std::cin;
using std::endl;
string ConvertMoney(double dNum)
{
string strResult;//要返回的字符串
char c_Digit[20];//c风格的字符数组
string strDigit;//输入的数字字符串
int iLength = 0;//输入的双精度数的长度
int iAddZero = 0;//加零标志
int iDigit = 0;//取出的数字
string str1[] = {"分","角","元","拾","佰","仟","万",
"拾","佰","仟","亿","拾","佰","仟","万","拾","佰","仟"};
string str2[] = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
vector<string> strUnit(str1,str1 + 18);//初始化向量
vector<string> strUpperNum(str2,str2 + 10);
sprintf(c_Digit,"%.0f",dNum*100);//将数字串换成c风格的数组
strDigit = c_Digit;//将字符数组的内容赋值给string变量
iLength = strDigit.length();//取得字符串的长度
if (iLength > 15 || iLength < 0)//如果输入的数字超出double类型数据的长度的话返回“error“
return "Error";
for (int i = 0; i < iLength; i++) {//将字符串逐位处理
iDigit = atoi(strDigit.substr(i,1).c_str());
if (iDigit == 0)//如果当前位为零,则将加零标志+1
iAddZero++;
else {
if (iAddZero > 0)//如果当前为不为0,且加0标志大于0
strResult += "零";//则在字符串中加入“零“
strResult += strUpperNum[iDigit];
iAddZero = 0;
}
//该位不为0||元位||亿位||万位
if ((iDigit != 0) || (iLength - i == 3) || (iLength - i == 11)||((iLength - i + 1)%8 == 0 && (iAddZero < 4)))
strResult += strUnit[iLength - i - 1];
}
if (strDigit.substr(strDigit.length() - 2,2) == "00")
strResult += "Õû";
return strResult;
}
int main()
{
double dLowerRMB = 0.0;
cout << "请输入要转换的人民币金额!" << endl;
cin >> dLowerRMB;
cout << "-------------------------------------------------" << endl;
cout << "您要转换的人民币小写金额为 " << "/n" << dLowerRMB << endl;
cout << "-------------------------------------------------" << endl;
string strUpperRMB = ConvertMoney(dLowerRMB);
cout << "大写金额为" << "/n" << strUpperRMB << endl;
cout << "-------------------------------------------------" << endl;
return 0;
}
如果大家不习惯使用标准C++中的string类的话,可以使用MFC中的CString来代替
string !