stringstream字符串到值的转换

#include "stdafx.h"
#include <sstream>

using namespace std;

template <typename T>
T StrToVer(const char* str)
{
    stringstream ss;
    T t;
    memset(&t, 0, sizeof(T));

    ss << str;
    ss >> t;
    
    return t;
}

int main()
{
    bool b1 = StrToVer<bool>("1") ;    //true
    bool b2 = StrToVer<bool>("0") ;     //false

    bool b3 = StrToVer<bool>("true") ;  //false <--- true,false的字符串不能转成bool型的值
    bool b4 = StrToVer<bool>("false") ; //false

    bool b5 = StrToVer<bool>("1a");     //true  <--- 只识别前面的数值
    bool b6 = StrToVer<bool>("0a");     //false

    bool b7 = StrToVer<bool>("11");     //false  <--- 非 1 都是false
    bool b8 = StrToVer<bool>("01");     //true
    bool b9 = StrToVer<bool>("2");     //false
    bool b10 = StrToVer<bool>("001");     //true

    
    unsigned char uc1 = StrToVer<unsigned char>("12");  //'1'   <--- 无符号char 也是识别一个字符, 不会识别成数值
    unsigned char uc2 = StrToVer<unsigned char>("-12"); //'-'
    unsigned char uc3 = StrToVer<unsigned char>("129"); //'1'
    unsigned char uc4 = StrToVer<unsigned char>("254"); //'2'
    unsigned char uc5 = StrToVer<unsigned char>("340"); //'3'


    char c1 = StrToVer<char>("12");  //'1'  <--- 有符号char 只识别一个字符
    char c2 = StrToVer<char>("-12"); //'-'
    char c3 = StrToVer<char>("129"); //'1'
    char c4 = StrToVer<char>("254"); //'2'
    char c5 = StrToVer<char>("340"); //'3'


    short int si1 = StrToVer<short int>("123");   //123
    short int si2 = StrToVer<short int>("-123");   //-123
    short int si3 = StrToVer<short int>("123.2");   //123
    short int si4 = StrToVer<short int>("1234567");   //0   <--- 溢出 返回0

    unsigned short int usi1 = StrToVer<unsigned short int>("123");   //123
    unsigned short int usi2 = StrToVer<unsigned short int>("-123");   //65413  <-- 有符号识别成无符号
    unsigned short int usi3 = StrToVer<unsigned short int>("123.2");   //123
    unsigned short int usi4 = StrToVer<unsigned short int>("1234567");   //0

    int i1 = StrToVer<int>("123");   //123
    int i2 = StrToVer<int>("-123");   //-123
    int i3 = StrToVer<int>("123.2");   //123

    unsigned int ui1 = StrToVer<unsigned int>("123");   //123
    unsigned int ui2 = StrToVer<unsigned int>("-123");   //4294967173
    unsigned int ui3 = StrToVer<unsigned int>("123.2");   //123

    float f1 = StrToVer<float>("12.3");     //12.3000002
    float f2 = StrToVer<float>("-12.3");    //-12.3000002
    float f3 = StrToVer<float>("012.3");    //12.3000002

    return 0;
}

以上是VC++编译器结果

posted @ 2018-03-09 09:49  镜水洞天  阅读(179)  评论(0编辑  收藏  举报