Páginas

sábado, 18 de junho de 2011

Classe para trabalhar com dados variantes (fracamente tipado) em C++

namespace str
{
    typedef char string[512];
    //#define giantString = new char[1000000000];
    void setString(char *str, const char* val)
    {
        unsigned int cont = 0;
        while (val[cont] != 0)
        {
            str[cont] = val[cont];
            cont++;
        }
        str[cont] = 0;

    }

    void setStr(char *str, const char* val)
    {
        setString(str, val);
    }

    unsigned int getLength(char * str)
    {
        unsigned int cont = 0;
        while (str[cont] != 0)
        {
            cont++;
        }
        return cont;
    }

    class TVariant
    {
        private:
            char *fvalue;
        public:
            void setInt(int value)
            {
                delete [] this->fvalue;
                this->fvalue = new char[20];
                itoa(value, this->fvalue, 10);
            }
            void setFloat(float value)
            {
                sprintf(this->fvalue, "%.4g", value);
                //sprintf(this->fvalue, "%.f", value );
            }
            void setString(char * value)
            {
                delete [] this->fvalue;
                this->fvalue =  new char[getLength(value)];
                setStr(this->fvalue, value);
            }
            void setChar(char value)
            {
                delete[] this->fvalue;
                this->fvalue = new char[1];
                this->fvalue[0] = value;
            }
            void setAdvancedString(TAdvancedString* value)
            {
                delete [] this->fvalue;
                this->fvalue =  new char[getLength(value->get())];
                setStr(this->fvalue, value->get());
            }

            int getInt()
            {
                return atoi(this->fvalue);

            }
            float getFloat()
            {
                return atof(this->fvalue);
            }
            char *getString()
            {
                return this->fvalue;
            }
            char getChar()
            {
                if (getLength(this->fvalue) > 0)
                {
                    return this->fvalue[0];
                }
                return 0;
            }
            void getAdvancedString(TAdvancedString* result)
            {
                result->set(this->fvalue);
            }
    };
}

Nenhum comentário:

Postar um comentário