Displaying Variables in GLUT
我正在尝试在我的GLUT窗口中显示变量的值。
也许像文本显示功能。
文字显示功能:
1 | renderBitmapString(0, 0.8, GLUT_BITMAP_TIMES_ROMAN_24,"hello"); |
定义为:
1 2 3 4 5 6 7 8 9 | void renderBitmapString(float x, float y, void *font, char *string) { char *c; glRasterPos2f(x,y); for (c=string; *c != '\0'; c++) { glutBitmapCharacter(font, *c); } } |
谢谢
您可以使用sprintf将变量打印到char []中,
1 2 | char buffer[256]; sprintf(buffer,"%s", myVariable); |
然后在其上调用renderBitmapString。
您可以这样定义函数和变量:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // 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]); } |
您可以使用如下所示的功能:
1 | print_str(text_x, text_y, GLUT_BITMAP_TIMES_ROMAN_24,"%s %d x %d", text, text_x, text_y); |
首先,可以使用c_str将普通的C ++字符串转换为char *:http://www.cplusplus.com/reference/string/string/c_str/但是,请注意,这为您提供了const char *,因此您将 必须使用const_cast()。
1 2 | string a ("Hello"); renderBitmapString(0, 0.8, GLUT_BITMAP_TIMES_ROMAN_24, const_cast<char*>(a.c_str())); |
IMO很丑。
其次,我不会在C ++程序中使用char *。 相反,您可以通过多种方式修改过程。 就个人而言,我将使用字符串迭代器。
1 2 3 4 5 6 7 8 9 10 11 | 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); |