Section 20.7 Printing to Strings
Suppose you wanted to store a file name in a string (in order to be able to work with the file) and you had the user enter the name (such as "importantFile") but you then wanted to add the file extension (such as ".txt") to this name. Here is a clever way to create such a custom string: You can actually "print" to a string using the
sprintf()
function which basically works exactly the same as printf()
! Here is the exact format:sprintf(dest, format_string, print_list);
So in the above example you could use something like
sprintf(fileName, "%s.txt", userEntry);
to accomplish the creation of the desired file name.Usage of
sprintf()
requires the standard library and with that the inclusion of this line at the top of your code:#include <stdlib.h>