CodingBison

This page provides a brief discussion of some of the common print functions (printf(), sprintf(), and snprintf()) along with the input function (scanf()). These functions are published via the "stdio.h" header file.

printf()

A printf() function takes various arguments, where the first argument determines how many more arguments are present. The first argument consists of format specifiers (like %d, %f) and the printf() replaces all the format specifiers present in the first string with the values that follow. Thus, "printf("This is a trial: %d\n", 100);" would evaluate to "This is a trial: 100" because printf would replace "%d" specifier in the first string with the value of 100.

The printf() function supports formats for various types: (a) %d and %i for integers, (b) %u for unsigned int values, (c) %x and %X for hexadecimal (the upper case prints hexadecimal numbers in upper case), (d) %f for float and double (fractional numbers), (e) %o for octal, (f) %c for char, (g) %s for strings, (h) %p for pointers, and (i) %% for the character % itself.

In fact, printf() function is expressive and allows us to add a lot more details to the basic output type. A generic syntax for printf() function is of the form: "%[flags][width][.precision][length]type".

The flag can be either "+" or "-". When we specify "+", it means that the printf should print the sign of the numeric value. The "-" sign means something very different -- it represents left padding for the output.

The width attribute specifies the number of decimal values that we want to pad with numbers. For padding (the total characters for the output), we can specify "%10d", which means that the total output character would be 10. By default, padding is done on the left side. We can specify "%-10d" to specify padding on the right side.

The precision attribute specifies the number of decimal values that we wish to print for fractional numbers. Thus, a value of "%.4f" means that we should print 4 decimal values for the float. If the input has additional decimal values, then it is truncated.

The length attribute allows us to tell printf, if we are passing a value that has a more specific length. For example, passing "l" means the value is a long integer and passing "ll" means the value is a long long integer.

With that, let us see an example that prints various types of variables using printf(). It also illustrates both padding and the number of decimals that we want to print for a float.

 #include <stdio.h>

 int main() {
     float var_float = 100.12345;
     int var_int = 1000;

     /* Left-padding of 20 characters and printing 4 decimal values */
     printf("The value of var_float is %20.4f\n", var_float);

     /* Right-padding of 20 characters and printing 4 decimal values */
     printf("The value of var_float is %-20.4f\n", var_float);

     /* Left-padding of 10 characters and printing 1 decimal values */
     printf("The value of var_float is %10.1f\n", var_float);

     /* Left-padding of 20 characters and need to print with the sign */
     printf("The value of var_int is %+20d\n", var_int);

     /* Printing 1 decimal value for an integer; basically the integer itself */
     printf("The value of var_int is %.1d\n", var_int);
     return 0;
 }

Note that for the last part, "%.1d" means printing one decimal value from an integer. However an integer would not have a decimal value, and so "%.1d" is essentially same as "%d". Here is the output:

 The value of var_float is             100.1235 
 The value of var_float is 100.1235             
 The value of var_float is      100.1 
 The value of var_int is                +1000
 The value of var_int is 1000 

It is also possible to pass the first string to printf in multiple lines. We can use this form if the first string is too long to fit on a single line. For this case, we can split the first string into multiple strings and place them in subsequent lines with no commas between these lines. Here is an example:

 #include <stdio.h>

 int main() {
     float var_float = 100.12345;
     int var_int = 1000; 
     char var_str[] = "Mona Lisa";

     printf("The value of var_float is %.4f.\n"
            "The value of var_int is %d.\n"  
            "The value of var_str is %s.\n", 
            var_float, var_int, var_str);
     return 0;
 }

And, here is the output:

 The value of var_float is 100.1235.
 The value of var_int is 1000.
 The value of var_str is Mona Lisa.

sprintf() and snprintf()

Function printf() has two modified variants: sprintf() and snprintf(). These functions allow us to print values to a string instead of the console. Here are their signatures:

 int sprintf(char *str, const char *format, ...)
 int snprintf(char *str, size_t n, const char *format, ...)

Both of these functions write the output to the str string; snprintf() is similar to sprintf() except that it writes only n bytes of output the str string.

As usual, let us see an example that demonstrates the usage of these two functions:

 #include <stdio.h>

 int main() {
     int var_int = 1000;
     char str[100];

     sprintf(str, "The value of var_int is %d", var_int);
     printf("[sprintf]: %s\n", str);

     snprintf(str, 10, "The value of var_int is %d", var_int);
     printf("[snprintf]: %s\n", str);
     return 0;
 }

We provide the output below. We see that since we pass a small size (10 chars) to the snprintf(), the output stores only the first 10 chars of the str variable.

 [sprintf]: The value of var_int is 1000
 [snprintf]: The value

scanf()

The scanf() function allows us to receive input from the console/command-prompt. The scanf() function takes address of variables as input and stores the input provided by console at that address.

Let us see an example.

The following code defines two variables, var_int and var_float and uses scanf to read values into these two variables. The scanf function takes "&var_int" and "&var_float" as input; these are pointers and not variables themselves (more on pointers in subsequent pages!). The "&" sign is important; missing it will likely crash your program. Some of us have learned this the hard way!

 #include <stdio.h>

 int main() {
     int var_int;
     float var_float;

     scanf("%d %f", &var_int, &var_float);
     printf("The value of var_int is %d \n", var_int);
     printf("The value of var_float is %-20.4f \n", var_float);
     return 0;
 }

In the output (which is typically a console), we need to type in inputs to the int and the float; in the output below, the "10000 1000.23232" is the input that we type on the command line. This input should be provided in the same order as expected -- an integer followed by a float. After accepting the input, the program simply prints these values back on the console.

 $ gcc scanf.c -o scanf
 $ 
 $ ./scanf 

 10000 1000.23232
 The value of var_int is 10000 
 The value of var_float is 1000.2323   
 $ 




comments powered by Disqus