一个字符串转换类

简介:
在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;
}

本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2007/11/18/963518.html,如需转载请自行联系原作者
目录
相关文章
|
2月前
|
安全 Java 索引
Java字符串类详解
Java字符串类详解
26 1
|
2月前
|
JavaScript 前端开发 API
|
2月前
复杂的数据类型如何转成字符串!
复杂的数据类型如何转成字符串!
|
2月前
字符串常用方法
字符串常用方法
|
2月前
|
JSON 数据格式
Json字符串与QVariantList 对象相互转换
Json字符串与QVariantList 对象相互转换
37 0
|
7月前
|
BI C# 数据安全/隐私保护
C# 字符串常用方法的详细讲解和应用
C# 字符串常用方法的详细讲解和应用
|
8月前
|
JSON 数据格式
json对象转字符串和字符串转对象的方法
json对象转字符串和字符串转对象的方法
52 0
|
10月前
|
存储 Java 对象存储
字符串相关的类
字符串相关的类
26 0
|
10月前
|
JSON fastjson 程序员
Json字符串转成对象
Json字符串转成对象
106 0