1. Computing & Technology

Discuss in my forum

Programming Games in C - Tutorial Two on Star Empires

By , About.com Guide

5 of 5

Formatted Text with Printf

The printf statement is used to print text to the screen and lets you create markers in the text using the % char combined with another letter such as %i to show where the value of a specified vriable should be inserted in the text. In combination with the gotoxy() function (that positions the onscreen cursor), this is how most of the game's screen display is created. For more details on printf see this C tutorial.

However for some of the generated messages, it is necessary to first build up the string in memory and this is what the sprintf() function does. It's used in SendaMessage2 (shown below) and other places. Sprintf has one extra parameter at the start which is a string variable (in this case of type message). The output from sprintf goes into the string variable which can then be printed out using printf.

/* writes a message with a single int parameter */
void SendaMessage2(char * msgtext,int x) {
  char buffer[100];
  sprintf(buffer,"%s %i",msgtext,x) ;
  SendaMessage(buffer) ;
}

If you are wondering why the first parameter uses a pointer (the * after a type means it's a pointer to that type), ie it's char * msgtxt and not message msgtxt, it's because message is fixed length and char * takes any length. Most of the time that won't matter but it is more flexible

Use of pointers as strings

In this tutorial, I'm not covering pointers (example char *) but they are used just as if they were strings. You will see a few string declaration that use pointers ie in SendaMessage/SendaMessage2 and other places, with declaration like this:

char * msgtext

But for now read this as being just like a string declaration, as if it was written

string message

Also in the GetInput function where the variable back is declared:

char * back ="\b \b";

again think of it as being like this:

string back ="\b \b";

When functions with a char * parameter are called, you can pass in a string in double quotes for example:

SendaMessage("You have captured ten systems") ;
Note:

The sprintf function is nowadays regarded as unsafe to use because it doesn't limit output. See this C tutorial on text file handling for more details about sprintf.

Special Control Chars

If you see a backslash followed by a single letter like \b, or \t \n \r \0 etc then these are special characters that don't print but affect the cursor or mark the end of a string (\0). The main ones are \b - backspace, \n and \r (carriage return and linefeed, usually used together to move the cursor down a line), \t (tab).

Conclusion

The next tutorial will look at the combat, computer AI etc in Star Empires.

©2012 About.com. All rights reserved.

A part of The New York Times Company.