Often you need a formatted string like the one created by a printf, but you do not want to display that. Rather you want to store it in a buffer for using it at some point latter.
Sprintf is a handy library function that achieves the above goal and helps with a lot of string and other variables manipulation. The best part is that if you know printf well as covered in the previous two tutorials i.e.
there is little required to understand or use it.
I would start with the function prototype which might look a little complex but it is very easy to get used to with.
int sprintf(char *result, const char *format, ….);
The only thing different from a printf is the initial ‘result’ parameter.
It also creates a formatted string exactly similar to printf. However, printf outputs that on the standard output or console, whereas sprintf stores it in a buffer called result.
Let’s take a look at a simple example
int a=15; char *b = "there"; double d = 20.55; char buff; // buff is large enough to hold the entire formatted string sprintf(buff, "Hi %s int a = %d double d = %f\n", b, a, d); printf(buff);
It is important to note that the caller should provide the memory for result. Also a terminating null or ‘\0’ is automatically inserted at the end of the string.
However, for string to be printed on a separate line we explicitly inserted a ‘\n’ at the end similar to how we often do with printing via printf. Of course this could have been inserted in the printf statement too, but since in the example above, we haven’t used a format string in printf and rather simply display the contents of ‘buff’ so adding the newline i.e.’\n’ in sprintf was much cleaner.
Detecting buffer overflow
Like printf, sprintf returns the number of characters copied to the buffer excluding the terminating ‘\0’ or in case of a failure it returns a negative number.
So we can check for a buffer overflow with something like
int num = sprintf(buff, "Hi %s int a = %d double d = %f\n", b, a, d); if(num >= 50 – 1 || num < 0) // remember 50 is the size of buff printf(“Buffer overflow\n”);
Integer / Double to string conversion
Now some practical usage for e.g. converting an integer or a double to a string i.e.
Similarly concatenating two strings (i.e. substituting strcat with more options like may be inserting a hyphen in between)
char * fir = "first str"; char * sec = "second str"; char res; sprintf(res, "%s ---- %s", fir, sec); printf("%s\n", res);
Append to original string
The scenario where original string needs to be appended with another
char res = "original str"; char * sec = "second str"; sprintf(res, "%s -- append -- %s", res, sec); printf("%s\n", res);
Note that ‘res’ or string to be modified is always an array i.e. declared with  rather than as a string constant i.e. char *sec = “string”; because array can be modified whereas string constant cannot.
A similar and very close variant is fprintf. Instead of a char array / buffer as the first parameter, fprintf takes a FILE * parameter. Therefore the printf style formatted string is written to a file.
FILE * fp = fopen("test.txt", "w"); int sec = 100; fprintf(fp, "Hi there %d", sec); fclose(fp);
The above code will create a file test.txt in the current working directory and write the string “Hi there 100” on a single line. In real applications, one needs to test fp for NULL before moving forward.
This function also stores the formatted string to a buffer with one additional parameter. The second parameter after the buffer / char array pointer is length of the buffer. This additional parameter is a size_t integer i.e.
char res; int sec = 5; snprintf(res, 10, "Hi hello %d", sec); printf("%s\n", res);
The above code would only print “Hi hello”. However, if the size (of res and second param in snprintf call) is increased to say 14 it would display the whole string.
The principle here is that 10-1 is the maximum number of elements snprintf would copy to res. After that it prepends the null terminator. If the string is longer than 9 characters, the remaining part is truncated. To see this in action, execute above code on some non-windows system.
Important Note for Windows / Visual Studio
Snprintf is part of C99 standard whereas visual studio only implements C89 standard. Hence snprintf would be undefined in VS. However, you can use the following workaround.
#if _MSC_VER #define snprintf _snprintf #endif
But note that even after the above change, on window it does not do automatic truncation and rather prints garbage characters. Snprintf is now part of C++11 standard too so hopefully it will soon be implemented across VS too.