Reader small image

You're reading from  Learn C Programming. - Second Edition

Product typeBook
Published inAug 2022
PublisherPackt
ISBN-139781801078450
Edition2nd Edition
Right arrow
Author (1)
Jeff Szuhay
Jeff Szuhay
author image
Jeff Szuhay

Jeff Szuhay is the principal developer at QuarterTil2 which specializes in graphics-rich software chronographs for desktop environments. In his software career of over 35 years, he has engaged in a full range of development activities from systems analysis and systems performance tuning to application design, from initial development through full testing and final delivery. Throughout that time, he has taught computer applications and programming languages at various educational levels from elementary school students to university students, as well as developed and presented professional, on-site training.
Read more about Jeff Szuhay

Right arrow

Chapter 19: Exploring Formatted Output

In previous chapters, all the input was provided within each program and all the output was sent in rather simple forms to the console (screen). In this chapter, we will expand on more sophisticated output formatting. However, what if we need a precise layout of numbers and text? We saw in Chapter 15Working with Strings, how to precisely generate a table of ASCII characters. With full knowledge of the possibilities of output formatting, very precise tables of numbers can be created. Furthermore, other kinds of precisely formatted documents can be generated, such as invoices and product price lists, for example.

The C printf() function provides a rich set of formatting options, far beyond what we have used up to this point. We can format numbers—both integers and decimal numbers—characters, and strings in many ways. In this chapter, we will explore, primarily through examples, the various ways in which...

Technical requirements

Continue to use the tools you chose in the Technical requirements section of Chapter 1, Running Hello, World!.

The source code for this chapter can be found at https://github.com/PacktPublishing/Learn-C-Programming-Second-Edition/tree/main/Chapter19.

Revisiting printf()

In previous chapters, whenever we printed the output of values to the console, we used relatively simple printf() formatting. However, printf() provides a very rich set of format specifiers for unsigned integers, pointers, signed integers, floats, doubles, characters, and strings. The programs given in this chapter will not provide an exhaustive example of every possible format specifier, nor of every possible combination of format specifiers. The programs provided are intended to serve as a starting point for your own continued experimentation.

Understanding the general format specifier form

So far, we have seen, for the most part, the simplest format specifier, %<x>, or occasionally even %<n><x>, where <x> is an output conversion type and <n> is the field width into which the value is printed. Depending on the value, the formatted output...

Using format specifiers for unsigned integers

Unsigned integers include positive integers in several base numbering systems, as well as pointer values. The first example program is unsignedInt.c, and it begins as follows:

#include <stdio.h>
int main( void )   {
  int smallInt = 12;
  int largeInt = (1024*1024*3)+(1024*2)+512+128+64+32+16+8+4+2+1;
  int negativeInt = -smallInt;
  unsigned anUnsigned = 130;
  // the other code snippets go here.
}

This code defines smallIntlargeIntnegativeInt, and unsigned int values. These will be used in each snippet that follows. After you type in the program and get it to run, you may want to experiment with different values for each of these variables.

Using unsigned integers in different bases

In the first code snippet, values in various base numbering systems are printed—these...

Using format specifiers for signed integers

Signed integers include integers that can have negative as well as positive values. The next example program is signedInt.c, and it begins as follows:

#include <stdio.h>
int main( void ) {
  int smallInt = 12;
  int largeInt = 0x7fffffff; // int32 max
  int negativeInt = -smallInt;
  unsigned anUnsigned = 130;
  long long int reallyLargeInt = 0x7fffffffffffffff; // int64 max
  // the other code snippets go here.
}

The values of smallIntlargeIntnegativeIntanUnsigned, and reallyLargeInt will be printed using various fields, precision, and alignment modifiers. Notice that largeInt is given a hexadecimal value that is the largest positive value a 32-bit integer can hold. Likewise, reallyLargeInit is given a hexadecimal value that is the largest positive value a 64-bit...

Using format specifiers for floats and doubles

Floating-point numbers are floats, doubles, and long doubles that can be expressed in a number of ways mathematically. They can be expressed naturally where there is a whole number part and a fractional part. They can be expressed in scientific notation where there is a coefficient raised to a power of 10, and it takes the 1.234567 x 10^123 form. The decimal point floats in such a way that the coefficient has a whole number part that is between 1 and 10 and the exponent is adjusted accordingly. C provides both of these formats.

The next example program is double.c, and it begins as follows:

#include <stdio.h>
int main( void )  {
  double aDouble = 987654321.987654321;
  // the other code snippets go here.
}

In this program, only one value is defined. Whenever the value is to be converted into float, it...

Using format specifiers for strings and characters

Our last program is character_string.c, and it begins as follows:

#include <stdio.h>
int main( void )  {
  char  aChar = 'C' ;
  char* pStr  = "Learn to program with C" ;
  
  // the other code snippets go here.
}

A character value, aChar, is defined with the C value, and a pStr string is defined to point to the start of the "Learn to program with C" string.

Using the string field width, precision, alignment, and zero-filling

When printing a string with the s conversion type, the alignment, minimum field width, and precision modifiers still apply, as follows: 

  printf("String output\n");
  printf("Specifier Formatted Value\n");
 &...

Summary

In this chapter, we fairly exhaustively explored output formatting for integers—both signed and unsigned—floating-point numbers, characters, and strings. Example programs that demonstrate the most common and useful combinations of print modifiers were also presented. However, not all the possible combinations or modifiers were demonstrated. These programs can and should be used as starting points for further experimentation for your specific output formatting needs. These programs are also valuable to verify how a particular C runtime performs because there are always minor differences from one implementation of C to the next. This is one place where differences appear most often.

In the next two chapters, we will explore getting simple input from the command line and then getting formatted and unformatted input from the console. We will then expand those topics in subsequent chapters even further for files, including reading various inputs from...

Questions

  1. What does printf() do?
  2. Do the values given to printf() change?
  3. What happens if you specify an invalid format string?
  4. Can printf() print structures?
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learn C Programming. - Second Edition
Published in: Aug 2022Publisher: PacktISBN-13: 9781801078450
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Jeff Szuhay

Jeff Szuhay is the principal developer at QuarterTil2 which specializes in graphics-rich software chronographs for desktop environments. In his software career of over 35 years, he has engaged in a full range of development activities from systems analysis and systems performance tuning to application design, from initial development through full testing and final delivery. Throughout that time, he has taught computer applications and programming languages at various educational levels from elementary school students to university students, as well as developed and presented professional, on-site training.
Read more about Jeff Szuhay