linux C++ number and character conversion

1. Number ===> 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);

 

/**
 * Convert the specified data to a string
 * @param t the data to be converted to a string
 * @return string
 */
template<class T> string str(T t) {
    ostringstream os;
    os.precision(numeric_limits< T>::digits10);
    os << t;
    return os.str();
}

 

 

/**
 * Convert the value to a string
 * @param t the data to be converted to a string
 * @param radix Numerical base
 * @return string
 */
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 ===> other types of numbers

 

 

/**
     * 将字符串转为 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));

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326683797&siteId=291194637