一个字符串转换类

本文介绍了一个C++类,能够自动将字符串数据转换为各种数值类型,如整型、浮点型等,支持多种进制输入。通过操作符重载实现了不同类型间的便捷转换。

C++中将字符串类转换为整型,浮点型并不像java,C#那样简单,这是件烦心的工作,而且不同的函数接口让代码维护起来也麻烦,所以写个自动进行字符串转换成所需要的类型的程序很有意义,下面这个类只有加入你想要的类型,并为之提供操作符重载就可以了。

注:如果你没有使用boost库,把#define USE_BOOST_LIBS注释掉

字符串转换类


// StringAutomaticCast.cpp : Defines the entry point for the console application.
//
#include <stdio.h>

#include <string>


#include 
"StringAutoCast.h"

/**
 * @brief Read data from a file and automatically convert it to return data type
 * 
 * @param format specify the format of read data (only for inter-like data (int, short, char, long,)
 *
 * @return CStringAutoCast 
 
*/
CStringAutoCast ReadDataFromFile(CStringAutoCast::E_format format
= CStringAutoCast::kDec)
{
    
/*
        here put some code that read a file (txt, xml or whatever you want) and 
        extract    data as std::string csReadFromFile
    
*/
    
const std::string csReadFromFile = "230";
    
return CStringAutoCast(csReadFromFile, format);
}
int main(int argc, char* argv[])
{
    
int a            = ReadDataFromFile();
    
float b            = ReadDataFromFile();
    unsigned 
char c = ReadDataFromFile();
    
long d            = ReadDataFromFile(CStringAutoCast::kOct); //specifies that the string read is in Octal format
    unsigned long e    = ReadDataFromFile(CStringAutoCast::kHex); //specifies that the string read is in Hexadecimal format
    std::string   f = ReadDataFromFile(); 

    
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值