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 21: Exploring Formatted Input

Using console command-line arguments to get string input into our running programs is often handy, but not very useful if we want to read lots of values of any data type while our program is running. To do that, we need to explore how to use formatted input. Formatted input is the opposite end of the pipe, so to speak, to formatted output. Just as we can use formatted output with print(), various value formats can be easily read to the console by using scanf(). Both of these functions do the heavy lifting of converting values into desired output strings or, conversely, converting input character strings into desired values.

To understand input formatting, we will need to first understand the concept of streams. We will then use the technique of experimentation—or, more specifically, trial and observation—to discover and verify our understanding of how C input streams operate. We will later expand...

Technical requirements

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

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

Introducing streams

In the simplest terms, a stream is a sequence of bytes transferred in one direction from its source to its target. We have already discussed the abstract concept of an execution stream, or the flow of compiled central processing unit (CPU) instructions from memory to the CPU. An execution stream is created when we successfully compile our source code files into an executable file. It is initiated when the program is invoked from the command line and flows until the program stops.

In the console, the input stream transfers bytes—in this case, characters—from the keyboard to our program's memory. The console's output stream transfers characters from our program's memory to the screen. A console, therefore, consists of a keyboard source stream for input and a screen destination stream for output. We can think of it simply as a pair of I/O streams.

The standard console is enhanced by...

Reading formatted input with scanf()

In Chapter 19Exploring Formatted Output, we exhaustively explored the printf() output specifiers using a variety of programs to demonstrate how these specifiers work. We can reuse much of that knowledge for input specifiers.

The input specifiers for scanf() are similar in syntax and meaning to the output specifiers of printf(), except for a few differences. Therefore, it is best to consider the format string specifiers for printf() and scanf() as only vaguely similar; do not rely on the documentation for one as a guide for the other.

The following differences should be noted:

  • printf() accepts precision specification, while scanf() does not.
  • printf() accepts the -+<space>0, and # flag specifiers, while scanf() does not.
  • Note that the input strings may have the -+, and/or # characters...

Using internal data conversion

It should be fairly obvious that the ability of printf() to convert binary values into strings and of scanf() to convert strings into binary values is very powerful. These facilities are not constrained to console streams, nor are they constrained to file streams. Whenever we need to carry out internal data conversions, we have the same facilities available to us with the related sprintf() and sscanf() functions. Rather than use streams, these functions use strings—arrays of characters—as their initial input and our resultant output. 

We have seen how scanf() can be finicky. One way to mitigate irregular or troublesome input is to read that input into a large string buffer and then process that string buffer in various ways with sscanf()

The function prototypes for sprintf() and scanf() look like this:

int sprintf( char* buffer , const...

Exploring unformatted I/O

Not every string input needs to be converted into some binary value. Often, we simply need to read or write strings without any additional formatting. There is a family of unformatted string I/O functions that can be used to read or write entire lines of characters without any formatting applied. However, these functions require each string to be formed into lines. A line is loosely defined as a string that is terminated by the <newline> character. Each of these has a console version as well as a file/stream version. For the remainder of this chapter, we will briefly explore this family of functions. 

Getting the string I/O to/from the console

To read and write a line of text, there are the puts() and gets() console functions and their stream equivalents, fputs() and fgets(), as shown in the following table:

The puts() and fputs() functions...

Summary

Just as we thoroughly explored formatted output in an earlier chapter, in this chapter, we nearly exhaustively explored formatted input. We began with a new understanding of I/O streams. We learned how a stream is a flow of bytes from a source to a destination. For the console, the streams are the pre-defined stdinstdout, and stderr variables. We also learned how nearly all I/O functions have multiple forms, depending on which stream is being used.

Once we learned about streams, we then began our exploration of input stream format specifiers. Much of what we learned is borrowed from our exploration of output format specifiers. We wrote simple programs to explore how to input integers, decimal numbers, strings, and characters. Through the programs we wrote, we also learned about scan sets, input field width control, and the non-assignment specifier. All of these expanded our ability to convert various forms of input data streams. After all that...

Questions

  1. What is a stream?
  2. Are the input specifiers for scanf() identical to the output specifiers for printf()?
  3. List three ways to get input from the console and convert that input to the desired data type.
  4. When should we use gets()?
  5. What are preferred alternatives to gets()?
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 €14.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