tags:

views:

759

answers:

5

I am trying to copy the value in bar into the integer foo.

This is what I have so far. When I run it I get a different hex value. Any help would be great.

int main()
{

    string bar = "0x00EB0C62";

    int foo = (int)bar;

    cout << hex << foo;
    ChangeMemVal("pinball.exe", (void*) foo, "100000", 4);

    return 0;
}

So the output should be 0x00EB0C62.

+1  A: 

when you cast a string as an int, you get the ascii value of that string, not the converted string value, to properly convert 0x00EB0C62, you will have to pass it through a string parser. (one easy way is to do ascii arithmetic).

yx
+2  A: 

atoi should work:

string bar = "0x00EB0C62";

int foo = atoi(bar.c_str());
scottm
should be atoi(bar.c_str())
Ron Warholic
It doesn't work if there are characters such as 'x' is in the string isn't it?
Naveen
It didn't work for me. It returned 0.
+2  A: 

Previous SO answer.

alxp
+1  A: 

This is what the string streams are for, you want to do something like this.

#include< sstream>
#include< string>
#include< iostream>
int main()
{
    std::string bar="0x00EB0C62";

    int foo=0;

    std::istringstream to_int;
    to_int.str(bar);
    to_int>>foo;

    std::cout<<std::ios_base::hex<<foo<<std::endl;;

    .
    etc.
    .

    return EXIT_SUCCESS;
}

That should do the trick. Sorry if I got the ios_base incorrect I can't remember the exact location of the hex flag without a reference.

James Matta
+2  A: 

Atoi certainly works, but if you want to do it the C++ way, stringstreams are the way the go. It goes something like this, note, code isn't tested and will probably not work out of the box but you should get the general idea.

int i = 4;
stringstream ss;
ss << i;
string str = ss.str();
jimka