Basics of Formatted Input/Output

Concepts


Output with printf

Recap

Conversion Specifiers

A conversion specifier is a symbol that is used as a placeholder in a formatting string. For integer output, %d is the specifier that holds the place for integers.

Here are some commonly used conversion specifiers (not a comprehensive list):

  %d    int (signed decimal integer) 
  %u    unsigned decimal integer 
  %f    floating point values (fixed notation) - float, double 
  %e    floating point values (exponential notation) 
  %s    string 
  %c    character  
A more comprehensive list is found in Deitel, Chapter 9

Printing Integers

Printing Floating-point numbers

Printing characters and strings

output.c -- contains all of the above sample outputs. Try running it yourself
 


scanf

Basics

Example

input1.c -- linked here
#include <stdio.h>

int main()
{
 int i;
 float f;
 char c;

 printf("Enter an integer and a float, then Y or N\n> ");
 scanf("%d%f%c", &i, &f, &c);

 printf("You entered:\n");
 printf("i = %d, f = %f, c = %c\n", i, f, c);

}

Sample run #1

User input underlined, to distinguish it from program output
Enter an integer and a float, then Y or N
> 34 45.6Y
You entered:
i = 34, f = 45.600, c = Y

Sample Run #2

Enter an integer and a float, then Y or N
> 12 34.5678 N
You entered:
i = 12, f = 34.568, c =  
Note that in this sample run, the character that was read was NOT the letter 'N'. It was the space. (Remember, white space not skipped on character reads).

This can be accounted for. Consider if the scanf line looked like this:

 scanf("%d%f %c", &i, &f, &c);
There's a space betwen the %f and the %c in the format string. This allows the user to type a space. Suppose this is the typed input:
 12 34.5678 N
Then the character variable c will now contain the 'N'.

input2.c -- a version of the example with this change is linked here
 

Interactive Input

You can make input more interactive by prompting the user more carefully. This can be tedious in some places, but in many occasions, it makes programs more user-friendly. Example:
  int age;
  double gpa;
  char answer;

  printf("Please enter your age: ");
  scanf("%d", &age);
  printf("Please enter your gpa: ");
  scanf("%lf", %gpa);
  printf("Do you like pie (Y/N)? ");
  scanf("%c", %answer); 

A good way to learn more about scanf is to try various inputs in various combinations, and type in test cases -- see what happens!


Deitel Ch.9 Examples