簡體   English   中英

在Window C ++中顯示文本

[英]Displaying Text to Window C++

我正在嘗試在一款小型且非常基本的游戲上向屏幕顯示分數。

我使用此功能來顯示單詞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); }
}

我使用以下drawBitmapText("score: ",score,0,1,0,10,220,0);調用上述function()drawBitmapText("score: ",score,0,1,0,10,220,0);

它成功顯示了單詞Score:並且在正確的位置,但是我遇到的問題是在其旁邊包括表示分數的實際int

如何合並要顯示的int 我成功通過了。

我試過將其轉換為string/char並添加/連接它,但它僅顯示隨機字母...謝謝。

由於您使用的是C ++,因此開始使用C ++庫來處理字符串會容易得多。 您可以使用std::stringstream連接標題和得分。

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); 
   }
}

使用std::stringstream

例如

std::stringstream ss;

ss << "score: " << score;

然后打電話

ss.str().c_str();

輸出交流弦

您可以使用snprintf創建格式化的字符串,就像使用printf將格式化的字符串打印到控制台一樣。 這是一種重寫方式:

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM