将以字符串输入的阿拉伯数字转换为中文输出

例如:
输入n 输出
“18” “十八”
“103” “一百零三”
“13000” “一万三千”
“10002000” "一千万零二千”
(0<n<100000000)

#include <iostream>
#include <string>
#include <vector>
#include <sstream>

using namespace std;

string ConvertNum(const string &m){
	string out;
	vector<string> hanzi{ "零", "一", "二", " 三", "四", "五", "六", "七", "八", "九" };
	vector<string> danwei{ "", "十", "百", "千", "万", "十", "百", "千" };

	bool Prezero = false;    //标记连续多个0
	int len = m.length();
	for (auto i = 0; i < m.length(); ++i){
		int num = m[i] - '0';
		int danwei_index = --len;
		if (i == 0 && num == 1 && (danwei_index == 1 || danwei_index == 5)){
			out = out + danwei.at(danwei_index);
		}
		else if (num == 0){
			Prezero = true;
			if (danwei_index == 4){
				out = out + danwei.at(danwei_index);
			}
		}
		else{
			if (Prezero){
				out.append(hanzi.at(0));
			}
			out.append(hanzi.at(num));
			out.append(danwei.at(danwei_index));
			Prezero = false;
		}
	}
	return out;
}


int main(){
	
	cout << "请输入阿拉伯数字n(0<n<100000000):" << endl;
	string m;
	//cin >> m;
	//char * end;
	//int i = strtol(m.c_str(),&end, 10);
	//cout << i << endl;
	while (cin >> m){
		try{
			stringstream ss;
			ss << m;
			int s;
			ss >> s;    //string to int
			if (s < 0 || s >= 100000000){
				throw "Error";
			}
			break;
		}
		catch (char *str){
			cerr << str << ":输入不合法,请重新输入!" << endl;
		}
	}

	cout << ConvertNum(m) << endl;

	return 0;
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值