Exforsys

Home arrow Technical Training arrow C Tutorials

C Programming - Managing Input and Output Operations Page - 3

Page 3 of 3
Author:      Published on: 30th Mar 2006    |   Last Updated on: 16th Aug 2011

C Programming - Managing Input and Output Operations

Input Specifications for Real Number

Use the %f specifier to accept floating point values. Ironically enough, the %d specifier will not accept decimal places. In order to accept a real number you would need to make a scanf call as follows:

Sample Code
  1. scanf("%f", &anum);
Copyright exforsys.com


Ads

Assuming that anum has been declared as a float.

You could now take 2.98 from standard input and it would be stored as 2.98, rather than 2 if you had used the %d specifier.

Input Specifications for a Character

Accepting character input from standard input to the scanf function works just like it did with integers. You can take a single character, or a specified number of them.

Let us modify our example program scanf.c to accept characters instead of integers. If we change scanf call for accepting 3 integers to 3 characters all we have to do is change the specifier. Of course we also have to change anum to a character array, but you get the idea.

Sample Code
  1. scanf(%3c, anum);
Copyright exforsys.com


Printing One Line

You can print a single line to the standard output as shown below: 

Sample Code
  1. printf("Type a series of numbers and press enter.n");
Copyright exforsys.com


Note the newline added at the end of the string. That is so the cursor will move down to the next line. Still technically one line though.

Conversion Strings and Specifiers

The usage of printf is almost identical to the usage of scanf we have just talked about. Take a look at the prototype:

Sample Code
  1. int printf(const char *restrict format, ...);
Copyright exforsys.com


Printf takes specifiers and a variable number of arguments. You can enter a whole list of arguments and specifiers, just make sure they line up so you do not put the wrong value in the wrong variable.

You can also insert newline, as you may have seen throughout the tutorials thus far.

Let us make a call to printf that will print that same value:

Sample Code
  1. scanf("%f", &anum);
  2. printf("%f", anum);
Copyright exforsys.com


The above program is similar to the call to scanf to read a real number, the difference being that we did not have to pass anum by reference to printf.

Ads

Specifier Meaning

There are more specifiers than we have shown up until now.

  • %d, %i: signed integer values
  • %o: unsigned octal
  • %s: character array
  • %c: unsigned character
  • %f, %F: float
  • %ld: long
  • %x: lowercase hexadecimal
  • %X: uppercase hexadecimal
  • %e: exponential form for a double
  • %p: pointer
  • %a: unsigned integer


 
This tutorial is part of a C Tutorials tutorial series. Read it from the beginning and learn yourself.

C Tutorials

 

Comments