Tutorial 17 and sprintf...need help!

Started by
3 comments, last by _Titan_ 22 years, 7 months ago
For some reason, only way i can put text to the screen is by using tutorial 17 method. Fine, it works, whatever. Problem is, i cant print variables with the function. So, i though i''d be a smart guy and try to go around that problem by using sprintf. Here is the code char* TEXT; int SCORE = 0; sprintf(TEXT,"Score: %i",SCORE); glPrint(0,0,TEXT,0); Now this always gives me a windows error, BUT, if i just have something like TEXT = "Your score is 120931209"; glPrint(0,0,TEXT,0); It will work just fine. So why cant i use sprintf to add the variable to my string? How can i get it so i can print variables without having to recode the glprint function? I know there is a way. AGAIN, THIS IS THE ONLY WAY I CAN PRINT TEXT!!! DO NOT TELL ME TO USE THE OTHER METHODS PLEASE, THEY DONT WORK FOR ME!!!!
Advertisement
hi,

I guess the problem is that (1. case) TEXT is an uninitialized char pointer and when you try to copy some data into it, it will not work. (2. case) The compiler initializes the pointer, because you has given TEXT a value.

Just something like this:

char* TEXT=(char*)malloc(64);
int SCORE = 0;

sprintf(TEXT,"Score: %d",SCORE);
glPrint(0,0,TEXT,0);

and at the end of your program...
delete TEXT;

or

char* TEXT;
int SCORE = 0;
TEXT = new char[64];

sprintf(TEXT,"Score: %d",SCORE);
glPrint(0,0,TEXT,0);

and at the end of your program...
delete TEXT;
You havent allocated any memory for Text.

If you use

char Text[20]={0};
and then use

int SCORE = 0;

sprintf(TEXT,"Score: %i",SCORE);
glPrint(0,0,TEXT,0);

it will work fine

Im not sure but I think it would also work if you used char* Text=new char[20];

edit: you beat me to it yot



Edited by - Zeke on September 7, 2001 5:48:17 AM
Just my thoughts take them as you will. "People spend too much time thinking about the past, whatever else it is, its gone"-Mel Gibson, Man Without A Face
SWEET! Thnx yot, your code worked. Sorry zeke, i tried your code, but i got errors way worse than i got before You guys rule anyways though. Thnx a million, it worked perfect.
and don't forget to delete that memory the clean way when you have done
TEXT=new char[64]; // or the likes
use
delete [] TEXT;
although visual c will fix the delete some compilers won't and can cause mem leaks or worse!

sorry for the nitpicking but its a common mistake! (which i'm fond of doing myself too!) but if i can help nip it in the bud with other programmers its kewl! the [] are an indicator for the delete function that it is deleting an array of elements not just 1 object!

Edited by - Dyad Roth on September 8, 2001 5:20:15 PM

This topic is closed to new replies.

Advertisement