linux C++ 数字和字符的转换

1、数字===》string

USING_STD(string);
USING_STD(vector);
USING_STD(istringstream);
USING_STD(ostringstream);
USING_STD(ends);
USING_STD(setbase);
USING_STD(pair);
USING_STD(numeric_limits);

/**
 * 将指定数据转化为字符串
 * @param t 待转为字符串的数据
 * @return 字符串
 */
template<class T> string str(T t) {
    ostringstream os;
    os.precision(numeric_limits<T>::digits10);
    os << t;
    return os.str();
}

/**
 * 将数值转化为字符串
 * @param t 待转为字符串的数据
 * @param radix 数值进制
 * @return 字符串
 */
template<class T> string str(T t, int radix) {
    ostringstream os;
    os.precision(numeric_limits<T>::digits10);
    os << setbase(radix)<< t;
    return os.str();
}

2、string ===》 其他类型数字

/**
     * 将字符串转为 long,int,bool,short
     */
    template<class ValueType> static ValueType& fromString(const string& s,
            ValueType& value, int radix = 10) {
        istringstream is(s);
        is >> setbase(radix)>> value;
        if (is.fail()) {
            value = ValueType();
        }
        return value;
    }

 

3、to  double

returnstrtod(s.c_str(), 0);

4、to float

returnstatic_cast<float>(strtod(s.c_str(), 0));

猜你喜欢

转载自konin.iteye.com/blog/2396950