例如:
输入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;
}