c++ and allegro : convert int to const char*

hi guys, i want to make a GUI application for showing binary search tree using allegro..and i have a problem to convert int (traverse->id) to print it on the screen using allegro's function (textprintf_ex) because it needs a const char*..anyone can help me?

this is the snippet of the code..

void tree::inorder(node* traverse)
{
if(traverse != NULL)
{
inorder(traverse->left);
textprintf_ex(buffer,font,0,200,WHITE,-1,static_cast<const char*>(traverse->id));
inorder(traverse->right);
}

}
int Number = 123; // number to be converted to a string

string Result; // string which will contain the result

ostringstream convert; // stream used for the conversion

convert << Number; // insert the textual representation of 'Number' in the characters in the stream

Result = convert.str(); // set 'Result' to the contents of the stream

// 'Result' now is equal to "123"


hmmm...i got a little problem here..
why in my program the 'string' in the string Result cannot be read?
it says "string undeclared"
also, ostringstream cannot be read firstly, but i add std:: in front of it, and it can be read..
i also have added #include<string>..but it can't..
can u help me with the 'string' thing??
well...well..
the problem is solved..
but it becomes a run time error..
there is some mistake in result.c_str() i think...


void tree::inorder(node* traverse)
{
string result;
ostringstream convert;
convert<<traverse->id;
result = convert.str();

if(traverse != NULL)
{
inorder(traverse->left);
textprintf_ex(buffer,font,100,400,WHITE,-1,"%s",result.c_str());
inorder(traverse->right);
}
}
I, as well as a million other C++ programmers in the world, can assure you that std::string::c_str() works correctly.

Your code must be wrong.

(BTW: traverse->id will crash if traverse is NULL since you don't check for NULL until later)
Try putting the "numb to text conversion" after the NULL check.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void tree::inorder(node* traverse)
{
  if(traverse != NULL)
  {
    string result;
    ostringstream convert;
    convert<<traverse->id;
    result = convert.str();

    inorder(traverse->left);
    textprintf_ex(buffer,font,100,400,WHITE,-1,"%s",result.c_str());
    inorder(traverse->right);
  }
}
Topic archived. No new replies allowed.