c - 在 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);
有什么建议么?
解决方案
我整理了一下:
这就是我所说的:
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++);
}
谢谢你们!
编辑:释放内存以避免泄漏,如评论中所述。
推荐阅读
- java - 如何使用 checkstyle 或 PMD 强制执行构造函数注入?
- javascript - Discord bot命令不起作用返回错误
- python - Sanic Python:将文件发送到客户端后删除
- python - 在 windows 中使用 cv2 保存视频并播放
- sql-server - SQL Server - 将纪元转换为日期时间
- javascript - 嵌套列表到数组 - Eloquent JavaScript 第 4 章
- azure - 通过非交互式 powershell 脚本连接到 Microsoft Teams
- python - 如何加快第二个循环依赖于第一个循环的嵌套循环?
- svg - 关节:如何将 icomoon 图标包含到 rappid 的自定义形状中
- excel - 如何从这个excel单元格中的特定文本中提取内容