首页 > 解决方案 > 在 GLUT 中打印整数的函数 - 如何编写用于将 int 转换为 char 的函数?

问题描述

我正在学习 C,但在某些时候一切都变得太抽象了,所以我决定使用 OpenGL 来尝试更具体的涉及用户交互的事情。我也在努力确保我的代码是可移植的,所以我总是在我的 Mac Pro、Raspberry Pi 和旧的 Power Mac 上运行它。

我创建了一个小颜色表来帮助我的生活:

GLfloat white[3] = { 1.0, 1.0, 1.0 };
GLfloat red[3] = { 1.0, 0.0, 0.0 };
GLfloat green[3] = { 0.0, 1.0, 0.0 };
GLfloat blue[3] = { 0.0, 0.0, 1.0 };
GLfloat yellow[3] = { 1.0, 1.0, 0.0 };
GLfloat dark_gray[3] = { 0.2, 0.2, 0.2 };

以及以下打印文本的功能:

void printText(char *text, const GLfloat colour[3], float posX, float posY) {
    glColor3fv (colour);
    glRasterPos2f(posX, posY);
  
    while(*text){
       glutBitmapCharacter(GLUT_BITMAP_8_BY_13, *text++);
    }

}

例如,我这样称呼它:printText(fn, white, 0.90f, 0.92f); 而且效果很好!

根据我在论坛中找到的代码,我正在将整数转换为字符串以打印屏幕帧速率计数器,我想我很了解它在做什么:

int length = snprintf( NULL, 0, "%d", frame_number );
char *fn = malloc( length + 1 );
snprintf(fn, length + 1, "%d", frame_number );
printText(fn, white, 0.90f, 0.92f);

每次我想在屏幕上打印一个整数时,我都不想编写所有这些代码,但我所做的一切都不起作用。

char charToInt(int integer) {
int length = snprintf( NULL, 0, "%d", integer);
char *convertedInteger = malloc(length + 1);
snprintf(convertedInteger, length + 1,"%d", integer);
return convertedInteger;}

或者return *convertedInteger;当我尝试打电话时都崩溃了printText(convertedInteger,colour,posX,posY);

有什么建议么?

标签: cstringglut

解决方案


我整理了一下:

这就是我所说的: GLprintTextAndInteger("just a bunch of words", int_to_print, colour, posX, posY);

这是功能:

void GLprintTextAndInteger (char *text, int value, float colour[3], float posX, float posY) {
int length = snprintf(NULL, 0, "%s %i", text, value);
char *stringToPrint = malloc(length + 1);
snprintf(stringToPrint, length + 1, "%s %i",text,value);
printText(stringToPrint,colour,posX,posY);
free(printText);
}

然后它正确调用我在问题中提到的函数:

void printText(char *text, const GLfloat colour[3], float posX, float posY) {
glColor3fv (colour);
glRasterPos2f(posX, posY);

while(*text){
   glutBitmapCharacter(GLUT_BITMAP_8_BY_13, *text++);
}

谢谢你们!

编辑:释放内存以避免泄漏,如评论中所述。


推荐阅读