简体   繁体   中英

Displaying Text to Window C++

I'm trying to display a score to the screen on a small and very basic game.

I use this function to display the word Score: :

void drawBitmapText(char *string, int score, float r, float g, float b, float x,float y,float z) {  
   char *c;
   glColor3f(r,g,b);
   glRasterPos3f(x,y,z);
   for (c=string; *c != '\0'; c++) { 
        glutBitmapCharacter(GLUT_BITMAP_HELVETICA_10, *c); }
}

I call the above function() using: drawBitmapText("score: ",score,0,1,0,10,220,0);

It successfully displays the word Score: and in the right place, but the problem I'm having is including the actually int that represents the score next to it.

How do I incorporate the int to be displayed too? I pass it successfully.

I've tried converting it a string/char and adding/concatenating it but it just displays random letters... Thanks.

Since you are using C++ it's going to be so much easier to start using C++ libraries to work with strings. You can use std::stringstream to concatenate the caption and score.

using namespace std;

void drawBitmapText(string caption, int score, float r, float g, float b, 
   float x,float y,float z) {  
   glColor3f(r,g,b);
   glRasterPos3f(x,y,z);
   stringstream strm;
   strm << caption << score;
   string text = strm.str();
   for(string::iterator it = text.begin(); it != text.end(); ++it) {
        glutBitmapCharacter(GLUT_BITMAP_HELVETICA_10, *it); 
   }
}

use std::stringstream

for example

std::stringstream ss;

ss << "score: " << score;

then call

ss.str().c_str();

to output ac string

You can use snprintf to create a formatted string, the same way you use printf to print a formatted string to the console. Here's one way of rewriting it:

void drawBitmapText(char *string, int score, float r, float g, float b, float x,float y,float z) {
    char buffer[64]; // Arbitrary limit of 63 characters
    snprintf(buffer, 64, "%s %d", string, score);
    glColor3f(r,g,b);
    glRasterPos3f(x,y,z);
    for (char* c = buffer; *c != '\0'; c++)
        glutBitmapCharacter(GLUT_BITMAP_HELVETICA_10, *c);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM