cout << *static_cast<int*>(test);

test is a void pointer pointed to an int variable.
if i use:

cout << *static_cast<char*>(test);

i get just 1 character.
so how can i print the value directly to string?
if i use the string i get an memory error

Recommended Answers

All 7 Replies

It's a pointer to int, but you want to print a string... How exactly do you want that string to be represented?

imagine that int is 200, i want print 200, but in a string way.. that's why the 'char *', but only prints 1 character :(

cout << *static_cast<int*>(test);, in what way doesn't this print the int value "in a string way"?

imagine that int is 200, i want print 200, but in a string way

Do you mean that you want to store the int value in a std::string?

    int i = 12;
    void *test = &i;

    stringstream ss;
    string str;
    ss << *static_cast<int*>(test);
    ss >> str;
    cout << str << "\n";

:( sorry.. seems that i'm having communications problems :(

cout << *static_cast<string*>(test);

i know these line isn't corrected, but i want like these.
the type is int, but i want like a string("12").

Not sure which of these you want, all three have been mentioned before. Here are three possibilities. Maybe the third option is what you are looking for.

If test is really a pointer to an integer then in order to save it in std::string it has to be converted from int to string. streamstring is how that's done.

void foo(void* test)
{
   int* x = (int*)test;
   cout << *x;

   //or

   cout << *(int*)test;

   // or
   stringstream s;
   s << *(int*)test;
   std::string str;
   s >> str;
   cout << str;
}

int main()
{
   int x = 12;
   foo(&x);
}

sorry can i create a variable for recive the variable type?

see these:

class variant2
    {
    private:
        void *Vvariant=NULL;
    public:

        template<typename b>
        variant2 & operator = (b &value)
        {
            Vvariant=&value ;   
            cout<< typeid(value).name();
            return *this;
        }

        friend ostream& operator <<(ostream &os,const variant2 &obj)
        {
            //os <<*static_cast<int*> (obj.Vvariant);
            return os;
        }
    };

if is string prints 'Ss' if is int, prints 'i' and so on...
but can i create a variable like these:

typeid f;//the type isn't correct, but tell me if i can do that
f=typeid(value);

????

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.