C++金额的中文大写
学习、记录、成长。
这道题还是做了好半天的,踩了很多细节问题...以前拿C写的时候好像用函数为了存大写数字就整的乱七八糟,这次本以为用 string 会大有增进,不成想在各种修补下依旧变得乱七八糟。但我觉得框架还是很清晰 (\拍桌) 看代码就懂。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string big[] = {"整", "元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "万"};//整数单位
string money[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};//大写数字
string small[] = {"角", "分"};//小数单位
string data; //保存输入数据
string ans[2000]; //输出缓存
int res, big_len, small_len, num, fx, f0;//整数位长、小数位长、金额转换、小数位标记、零标记
char numm; //转换用中介
while (cin >> data)
{
fx = 0;
f0 = 1;
res = data.find(".");
if (res > 0) //这个if-else 判断是否有小数位
{
small_len = data.length() - 2 - res;
fx = 1;
big_len = res;
}
else
big_len = data.length();
int i, j, k1 = 0, k2 = 0; //分别用来遍历原字符串与答案字符串
for (i = 0; i < big_len; i++) //我是一个小裁缝、缝补本领强。。
{
numm = data[i];
num = numm - '0';
if (num == 0 && i == 0)
{
ans[0] = "零";
ans[1] = "元";
ans[2] = "整";
k1 = 2;
//cout << "零元整" << endl;
break;
}
if (num == 0)
{
if (k1 >= 2 && ans[k1 - 2] == "壹" && ans[k1 - 1] == "拾")
{
ans[k1 - 2] = ans[k1 - 1];
k1--;
if ((big_len - i) == 1 || (big_len - i) == 5 || (big_len - i) == 9)
ans[k1++] = big[big_len - i];
continue;
}
if ((big_len - i) == 1 || (big_len - i) == 5 || (big_len - i) == 9)
ans[k1++] = big[big_len - i];
if (f0 == 1)
{
f0 = 0;
}
}
else if (num > 0)
{
if (f0 == 0)
{
ans[k1++] = money[0];
f0 = 1;
}
ans[k1++] = money[num];
ans[k1++] = big[big_len - i];
}
}
if (fx)
{
i++;
for (j = 0; j <= small_len; i++, j++)
{
numm = data[i];
num = numm - '0';
if (num == 0)
{
if (f0 == 1)
{
f0 = 0;
}
}
else if (num > 0)
{
if (f0 == 0)
{
ans[k1++] = money[0];
ans[k1++] = small[j-1];
f0 = 1;
}
ans[k1++] = money[num];
ans[k1++] = small[j];
}
}
}
else
ans[k1++] = big[0];
for (k2 = 0; k2 < k1; k2++)
cout << ans[k2];
cout << endl;
}
//system("pause");
return 0;
}