开发者

Displaying Variables in GLUT

I'm trying to display the value of a Variable inside my GLUT window.

Perhaps something like the text display function..

Text Display Function:

renderBitmapString开发者_运维技巧(0, 0.8, GLUT_BITMAP_TIMES_ROMAN_24, "hello");

Defined as:

    void renderBitmapString(float x, float y, void *font, char *string) 
{  
  char *c;
  glRasterPos2f(x,y);
  for (c=string; *c != '\0'; c++) 
  {
    glutBitmapCharacter(font, *c);
  }
}

Thank you


You can print the variable into a char[] with sprintf,

char buffer[256];
sprintf(buffer,"%s", myVariable);

And then call the renderBitmapString on it.


First, a normal C++ string can be turned into a char * using c_str: http://www.cplusplus.com/reference/string/string/c_str/ However, note that this gives you a const char*, so you'll have to use const_cast().

string a ("Hello");
renderBitmapString(0, 0.8, GLUT_BITMAP_TIMES_ROMAN_24, const_cast<char*>(a.c_str()));

Pretty ugly IMO.

Second, I wouldn't use char * in a C++ program. Instead, you can modify your procedure in a number of ways. Personally, I would use a string iterator.

void renderBitmapString(float x, float y, void *font, string str) 
{
  glRasterPos2f(x,y);
  for (string::iterator c = (&str)->begin(); c != (&str)->end(); ++c) 
  {
    glutBitmapCharacter(font, *c);
  }
}

string a ("Hello");
renderBitmapString(0, 0.8, GLUT_BITMAP_TIMES_ROMAN_24, a);


You can define the function and variables like that:

// global variables
int text_x = 0, text_y = 0;
char text[] = "Text location:";

// to display strings with variables
void print_str(int x, int y, void *font, char *string, ...)
{
    int len, i;

    va_list st;
    va_start(st, string);
    char str[1024];
    vsprintf_s(str, string, st);
    va_end(st);

    glRasterPos2f(x, y);
    len = (int)strlen(str);
    for (i = 0; i < len; i++)
        glutBitmapCharacter(font, str[i]);
}

than you can use the function as shown below:

print_str(text_x, text_y, GLUT_BITMAP_TIMES_ROMAN_24, "%s %d x %d", text, text_x, text_y);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜