visual c++: convert int into string pointer

前端 未结 10 2299
既然无缘
既然无缘 2021-01-22 09:01

how to convert integer into string pointer in visual c++?

10条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-22 09:30

    You got homework? a generic one, tested if g++, http://effocore.googlecode.com/svn/trunk/devel/effo/codebase/addons/inl/include/impl/algo_impl.h :

    #ifdef __cplusplus
    
    static inline char *int2a_put(uintptr_t i, char *s)
    {
        do {
            *s++ = '0' + i % 10;
            i /= 10;
        } while (i);
    
        return s;
    }
    
    static inline void int2a_reverse(char *head, char *tail)
    {
        for (*tail = '\0'; --tail > head; ++head) {
            /* exchange */
            (*head) ^= (*tail);
            (*tail) ^= (*head);
            (*head) ^= (*tail);
        }
    }
    
    template
    static inline const char *int2a(t i, char *s)
    {
        char *p;
        char *ret = s;
        bool f = false;
    
        p = s;
        if (i < 0) { 
            *p++ = '-';
            ++ s;
            /* 
             * In limits.h, INT_MAX was defined as 
             *   maximum values a `signed int' can hold.
             * and LONG_MAX was defined as maximum values 
             *   a `signed long int' can hold. 
             */
            switch (sizeof(t)) {
            case 8:
                {
                    /* 
                     * Inject \p a to prevent from complaint 
                     *   of compiler.
                     */
                    ef64_t a = (ef64_t)i;
                    if (-LLONG_MAX > a) {
                        i = (t)LLONG_MAX;
                        f = true;
                    }
                }
                break;
            case 4:
            case 2:
            case 1:
                {
                    /* 
                     * Inject \p a to prevent from complaint 
                     *   of compiler. 
                     */
                    int a = (int)i;
                    if (-INT_MAX > a) {
                        i = (t)INT_MAX;
                        f = true;
                    }
                }
                break;
            default:
                break;
            }
            if (!f) {
                i = -i;
            }
        }
    
        p = int2a_put((uintptr_t)i, p);
    
        if (f) {
            ++ *s;
        }
    
        int2a_reverse(s, p);
    
        return ret;
    }
    
    /*
     * No "static" otherwise g++ complains 
     *   "explicit template specialization cannot have a storage class"
     */
    template<>
    /*static*/ inline 
    const char *int2a(uintptr_t i, char *s)
    {
        char *p = int2a_put(i, s);
    
        int2a_reverse(s, p);
    
        return s;
    }
    
    #else
    

提交回复
热议问题