I have a code with a function TextOut
that writes one char on the window every time with some delay. All was in normal but my program writes only part of string to the window. However sometimes program writes the whole text.
This function create wchar from char
char* cts(char c)
{
char *ptr = (char*)malloc(2 * sizeof(char));
ptr[0] = c;
ptr[1] = '\0';
return ptr;
}
void TextOut(SDL_Renderer *ren, TTF_Font *f)
{
SDL_Surface *sur;
SDL_Texture *tex;
static SDL_Rect rect;
static int32_t x;
//Checking if string is end
if (OUT_STRING[x] == '\0') return;
//Get a wide char from string
char *temp = cts(OUT_STRING[x]);
//Get the size of font
TTF_SizeText(f, temp, &rect.w, &rect.h);
sur = TTF_RenderText_Blended(f, temp, color)
free(temp);
tex = SDL_CreateTextureFromSurface(ren, sur);
SDL_RenderCopy(ren, tex, NULL, &rect);
SDL_RenderPresent(ren);
rect.x += rect.w;
x++;
SDL_FreeSurface(sur);
SDL_Delay(50);
}
int main(int argc, char* argv[])
{
/*
Initialization of Window, Renderer, Font and other things
*/
OUT_STRING = "We are waiting";
while (!quit)
{
while (SDL_PollEvent(&e) != 0)
{
TextOut(renderer, font);
if (e.type == SDL_QUIT) quit = true;
}
}
return 0;
}
The problem you describe is due to your event loop - you're calling your render function there. When your window is shown, several events are generated (SDL_WINDOWEVENT_EXPOSED, etc.), so your render function called severnal times, but not enough for your "whole" text. When more events arrives (mouse move, keypressed, window manipulations, ...) - you can see more. If that is undesired behaviour - you should use event loop for what it is, events handling, e.g.:
while (!quit)
{
while (SDL_PollEvent(&e) != 0)
{
if (e.type == SDL_QUIT) quit = true;
}
TextOut(renderer, font);
}
It is questionable how you're going to continue drawing after all characters are shown, or why you need malloc (you don't).