C++实现中文大写与阿拉伯数字的相互转换(类封装)

简介: C++实现中文大写与阿拉伯数字的相互转换(类封装)

要求和内容

编写控制台模式的程序,接收用户输入的整数,然后将其转换为中文大写金

额的形式。 例如:

输入: 1024

输出: 壹仟零贰拾肆

要求如下:

1)输入输出必须使用 cin、cout。

2)要求每个源文件仅包含单一功能模块。

3) 先设计测试用的例子,并在 test.cpp 中实现,然后实现代码。

4) 在实现上述要求的基础上,修改代码,使其可以转换小数形式的数据,例如输入 3.12时,转换为叁元壹角贰分。

5) 在实现上述要求的基础上,修改代码,使其在输入错误时,给出错误提示,并说明错误出现的位置。

calc.cpp

#include <iostream>
#include <sstream>
#include <string>
#include <stack>
//将string转换成wstring 
#include "calc.h"
using namespace std;
void Num2Uper::transform()
{
    string part_int;
    string part_dec;
    int point_pos = int(this->getNum().find('.'));
    //        cout<<"point_pos = "<<point_pos<<endl;
    if (point_pos == -1)
    {
        part_int = this->num_;
    }
    else
    {
        part_int = num_.substr(0, point_pos);
        part_dec = num_.substr(point_pos + 1);
    }
    int part_int_size = part_int.size();
    //        cout<<"part_int_size = "<<part_int_size<<endl;
    bool zero_flag = true; // flase表示有0
    bool prev_zero_flag = false; // false表示0位之前有非零数
    stack<string> result;
    for (int i = 0; i < part_int_size; ++i)
    {
        //            cout<<"i = "<<i<<endl;
        int tmp = int(part_int[part_int_size - i - 1]) - 48;
        if (i % 4 == 0)
        {
            if (tmp == 0)
            {
                if (!zero_flag && prev_zero_flag)
                {
                    result.push(digits_[0]);
                }
                result.push(unit_1[i]);
                zero_flag = false;
                prev_zero_flag = false;
            }
            else
            {
                //101
                if (!zero_flag && prev_zero_flag)
                {
                    result.push(digits_[0]);
                }
                result.push(unit_1[i]);
                result.push(digits_[tmp]);
                zero_flag = true;
                prev_zero_flag = true;
            }
        }
        else
        {
            if (tmp == 0)
            {
                zero_flag = false;
                continue;
            }
            else
            {
                if (prev_zero_flag && !zero_flag)
                {
                    //                        result.push(digits_[0]);
                    result.push(digits_[0]);
                }
                result.push(unit_1[i]);
                result.push(digits_[tmp]);
                prev_zero_flag = true;
                zero_flag = true;
            }
        }
    }
    string tmp;
    while (!result.empty())
    {
        tmp = result.top();
        result.pop();
        if (tmp == "亿" && result.top() == "万")
        {
            result.pop();
        }
        word_.append(tmp);
        //            result.pop();
    }
    if (point_pos == -1)
    {
        word_.append("");
    }
    else
    {
        word_.append("");
        for (int i = 0; i < part_dec.size(); ++i)
        {
            word_.append(digits_[int(part_dec[i]) - 48]);
            word_.append(unit_2[i]);
        }
    }
}
string Num2Uper::digits_[10] = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
string Num2Uper::unit_1[13] = { "", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟","万" };
string Num2Uper::unit_2[2] = { "角", "分" };

calc.h

#ifndef _CALC__H
#define _CALC__H
#include <iostream>
#include <sstream>
#include <string>
#include <stack>
#include <locale>
#include <codecvt>
#include <comdef.h>
using namespace std;
class Num2Uper
{
public:
    Num2Uper(const string& num)
    {
        /*此处应该检查num的值是否合法。
         * 如:
         *      1- 小于0
         *      2- 小数不合法
         *      3- 数字本身不合法
         *      4- 小数点是非法字符等
         * */
         //if (num.size()-)
        this->setNum(num);
    }
    Num2Uper()
    {
        this->num_ = nullptr;
        this->word_ = nullptr;
    }
    const string& getWord() const
    {
        return word_;
    }
    void setWord(const string& word)
    {
        Num2Uper::word_ = word;
    }
    const string& getNum() const
    {
        return num_;
    }
    void setNum(const string& num)
    {
        Num2Uper::num_ = num;
    }
    virtual ~Num2Uper()
    {
    }
private:
    string word_;
    string num_;
    //    static  string touper_[10]={"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
    //    static  string unit_[15] = { "万", "仟", "佰", "拾", "亿", "仟", "佰", "拾", "万", "仟", "佰", "拾","元", "角", "分"};
    static string digits_[10];
    static  string unit_1[13];
    static  string unit_2[2];
public:
    void transform();
};
wstring string2wstring(string str);
#endif // !_CALC__H

chinesetonum.cpp

#include<string>
#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
#include <sstream>
#include <stack>
#include "chinesetonum.h"
using namespace std;
/*wstring,使用的是wchar_t类型,这是宽字符,用于满足非ASCII字符的要求,例如Unicode编码,中文,日文,韩文什么的。
*/
wstring wsNum =
{ L"零壹贰叁肆伍陆柒捌玖" };
wstring wsUnit = { L"拾佰仟万亿" };
map<wchar_t, long long> m; //数字:零:0 一:1 ...
//单位: 十:10 百:100 ...
//建立wchar_t型到long型的映射
void buildMap() {
    for (int i = 0; i < wsNum.size(); ++i) {
        //      printf("wsNum[%d] = %s\r\n", i,wsNum[i]);
        m[wsNum[i]] = i;
    }
    int unit = 1;
    for (int i = 0; i < wsUnit.size(); ++i) {
        if (i == wsUnit.size() - 1) {
            unit *= 1e4;
        }
        else {
            unit *= 10;
        }
        m[wsUnit[i]] = unit;
    }
}
long long changeChinese2Int(wstring s) {
    reverse(s.begin(), s.end());
    long long ret = 0;
    long long curUnit = 1;
    for (auto c : s) {//输出一个数组的全部元素
        int n = m[c];
        if (n <= 9) {
            ret += n * curUnit;
        }
        else {
            if (n > curUnit) {
                curUnit = n;
            }
            else {
                curUnit *= n;
            }
        }
    }
    if (m[s.back()] > 9) {
        ret += curUnit; //针对不规范的输入,比如输入"十八",而不是"一十八"
    }
    return ret;
}

chinesetonum.h

#ifndef _CHINESETONUM__H
#define _CHINESETONUM__H
#include<string>
#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
#include <sstream>
#include <stack>
using namespace std;
class chinese_to_num {
public:
    void buildMap();
    long long changeChinese2Int(wstring s);
    void chinese_to_num_test(void);
};
void buildMap();
long long changeChinese2Int(wstring s);
#endif // !_CHINESETONUM__H

test.cpp

#include<string>
#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
#include <sstream>
#include <stack>
#include "chinesetonum.h"
#include "test.h"
#include "calc.h"
using namespace std;
void test0(void) {
  std::string s = std::to_string(42);
  cout << s << endl;
  if (s == "-1")
    return;
  Num2Uper num = Num2Uper(s);
  num.transform();
  cout << "人民币" << num.getWord() << endl;
}
void test1(void) {
  std::string s = std::to_string(10009);
  cout << s << endl;
  if (s == "-1")
    return;
  Num2Uper num = Num2Uper(s);
  num.transform();
  cout << "人民币" << num.getWord() << endl;
}
void test2(void) {
  std::string s = std::to_string(10.98);
  cout << s << endl;
  if (s == "-1")
    return;
  Num2Uper num = Num2Uper(s);
  num.transform();
  cout << "人民币" << num.getWord() << endl;
}
void test3(void) {
  std::string s = std::to_string(987654321);
  cout << s << endl;
  if (s == "-1")
    return;
  Num2Uper num = Num2Uper(s);
  num.transform();
  cout << "人民币" << num.getWord() << endl;
}
void test4(void) {
  std::string s = std::to_string(4100200);
  cout << s << endl;
  if (s == "-1")
    return;
  Num2Uper num = Num2Uper(s);
  num.transform();
  cout << "人民币" << num.getWord() << endl;
}
void test(void)
{
   test0();
   test1();
   test2();
   test3();
   test4();
   //chinese_to_num_test();
}
void chinese_to_num_test(void) {
  buildMap();
  vector<wstring> v_test = {
    L"捌",
    L"壹拾",
    L"拾捌",
    L"捌拾",
    L"捌拾贰",
    L"壹佰",
    L"捌佰零捌",
    L"壹仟零贰万零玖拾",
    L"贰仟亿零壹佰零壹万零贰佰",
    L"贰佰叁拾肆",
  };
  for (int i = 0; i < v_test.size(); ++i) {
    wcout.imbue(locale("chs"));
    wcout << v_test[i] << endl;
    long long ret = changeChinese2Int(v_test[i]);
    cout << ret << endl;
  }
}

test.h

#ifndef _TEST__H
#define _TEST__H
void test();
void chinese_to_num_test(void);
#endif // !_TEST__H

main.cpp

#include <iostream>
#include <sstream>
#include <string>
#include <stack>
#include <Windows.h>
#include <locale> 
#include "calc.h"
#include "test.h"
#include "chinesetonum.h"
using namespace std;
//wstring wsNum =
//{ L"零壹贰叁肆伍陆柒捌玖" };
//wstring wsUnit = { L"拾佰仟万亿" };
int main()
{
  cout << "数字转中文大写测试:" << endl;
     test();
   cout << "中文大写转数字测试:" << endl;
   chinese_to_num_test();
   cout << "\r\n" << endl;
    string str;
    while (1)
    {
        cout << "请输入数字金额:";
        cin >> str;
        if (str == "-1")
            break;
        Num2Uper num = Num2Uper(str);
        num.transform();
        cout << "人民币" << num.getWord() << endl;
         wcin.imbue(locale("chs"));
         wcout.imbue(locale("chs"));
         wstring str;
         cout << "请输入中文金额:";
         wcin >> str;
    long long ret = changeChinese2Int(str);
    cout << ret << endl;
    }
    return 0;
}

运行结果


目录
相关文章
|
7月前
|
编译器 C++ 开发者
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
|
3月前
|
人工智能 机器人 编译器
c++模板初阶----函数模板与类模板
class 类模板名private://类内成员声明class Apublic:A(T val):a(val){}private:T a;return 0;运行结果:注意:类模板中的成员函数若是放在类外定义时,需要加模板参数列表。return 0;
72 0
|
3月前
|
存储 编译器 程序员
c++的类(附含explicit关键字,友元,内部类)
本文介绍了C++中类的核心概念与用法,涵盖封装、继承、多态三大特性。重点讲解了类的定义(`class`与`struct`)、访问限定符(`private`、`public`、`protected`)、类的作用域及成员函数的声明与定义分离。同时深入探讨了类的大小计算、`this`指针、默认成员函数(构造函数、析构函数、拷贝构造、赋值重载)以及运算符重载等内容。 文章还详细分析了`explicit`关键字的作用、静态成员(变量与函数)、友元(友元函数与友元类)的概念及其使用场景,并简要介绍了内部类的特性。
154 0
|
5月前
|
编译器 C++ 容器
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
C++11为C++带来了革命性变化,引入了列表初始化、右值引用、移动语义、类的新默认成员函数和lambda表达式等特性。列表初始化统一了对象初始化方式,initializer_list简化了容器多元素初始化;右值引用和移动语义优化了资源管理,减少拷贝开销;类新增移动构造和移动赋值函数提升性能;lambda表达式提供匿名函数对象,增强代码简洁性和灵活性。这些特性共同推动了现代C++编程的发展,提升了开发效率与程序性能。
152 12
|
6月前
|
设计模式 安全 C++
【C++进阶】特殊类设计 && 单例模式
通过对特殊类设计和单例模式的深入探讨,我们可以更好地设计和实现复杂的C++程序。特殊类设计提高了代码的安全性和可维护性,而单例模式则确保类的唯一实例性和全局访问性。理解并掌握这些高级设计技巧,对于提升C++编程水平至关重要。
120 16
|
7月前
|
编译器 C语言 C++
类和对象的简述(c++篇)
类和对象的简述(c++篇)
|
6月前
|
编译器 C++
类和对象(中 )C++
本文详细讲解了C++中的默认成员函数,包括构造函数、析构函数、拷贝构造函数、赋值运算符重载和取地址运算符重载等内容。重点分析了各函数的特点、使用场景及相互关系,如构造函数的主要任务是初始化对象,而非创建空间;析构函数用于清理资源;拷贝构造与赋值运算符的区别在于前者用于创建新对象,后者用于已存在的对象赋值。同时,文章还探讨了运算符重载的规则及其应用场景,并通过实例加深理解。最后强调,若类中存在资源管理,需显式定义拷贝构造和赋值运算符以避免浅拷贝问题。
|
6月前
|
存储 编译器 C++
类和对象(上)(C++)
本篇内容主要讲解了C++中类的相关知识,包括类的定义、实例化及this指针的作用。详细说明了类的定义格式、成员函数默认为inline、访问限定符(public、protected、private)的使用规则,以及class与struct的区别。同时分析了类实例化的概念,对象大小的计算规则和内存对齐原则。最后介绍了this指针的工作机制,解释了成员函数如何通过隐含的this指针区分不同对象的数据。这些知识点帮助我们更好地理解C++中类的封装性和对象的实现原理。
|
6月前
|
安全 C++
【c++】继承(继承的定义格式、赋值兼容转换、多继承、派生类默认成员函数规则、继承与友元、继承与静态成员)
本文深入探讨了C++中的继承机制,作为面向对象编程(OOP)的核心特性之一。继承通过允许派生类扩展基类的属性和方法,极大促进了代码复用,增强了代码的可维护性和可扩展性。文章详细介绍了继承的基本概念、定义格式、继承方式(public、protected、private)、赋值兼容转换、作用域问题、默认成员函数规则、继承与友元、静态成员、多继承及菱形继承问题,并对比了继承与组合的优缺点。最后总结指出,虽然继承提高了代码灵活性和复用率,但也带来了耦合度高的问题,建议在“has-a”和“is-a”关系同时存在时优先使用组合。
307 6
|
6月前
|
编译器 C++
类和对象(下)C++
本内容主要讲解C++中的初始化列表、类型转换、静态成员、友元、内部类、匿名对象及对象拷贝时的编译器优化。初始化列表用于成员变量定义初始化,尤其对引用、const及无默认构造函数的类类型变量至关重要。类型转换中,`explicit`可禁用隐式转换。静态成员属类而非对象,受访问限定符约束。内部类是独立类,可增强封装性。匿名对象生命周期短,常用于临时场景。编译器会优化对象拷贝以提高效率。最后,鼓励大家通过重复练习提升技能!