scanf function in c, variations in conversion specifier

Post on 16-Apr-2017

270 views 4 download

Transcript of scanf function in c, variations in conversion specifier

Topic: Format specifiers for scanf() function

BY: K SAI KIRAN

Background of scanf() fun' : The usually used input statement is scanf () function. Syntax of scanf function is

scanf (“format string”, argument list); The format string must be a text enclosed in double

quotes. It contains the information for interpreting the entire data for connecting it into internal representation in memory.

Example: integer (%d) , float (%f) , character (%c) or string (%s).

Example: if i is an integer and j is a floating point number, to input these two numbers we may use

Output for the previous program:

The following shows code in C that reads a variable number of formatted decimal integers from the console

and prints out each of them on a separate line:

Output for the previous program:

Unusual conversion specifier: Example: The code

below reads characters and prints it back.

The unusal conversion code here is “ %[^\n] “ .

Output for the previous program:

Analyzing the unusual conversion specifier %[

This is the weirdest format specifier . It allows you to specify a set of characters to be stored away (likely in an array of chars). Conversion stops when a character that is not in the set is matched.

For example, %[A-E] means "match all alphabets A through E."

We can tell scanf() to match characters that are not in the set by putting a caret (^) directly after the %[ and following it with the set, like this: %[^A-C], which means "match all characters that are not A through C."

Example:

To match a close square bracket, make it the first character in the set, like this: %[]A-C] or %[^]A-C]. (I added the "A-C" just so it was clear that the "]" was first in the set.)

To match a hyphen, make it the last character in the set: %[A-C-].

So if we wanted to match all letters except "%", "^", "]", "B", "C", "D", "E", and "-", we could use this format string: %[^]%^B-E-].

THANK YOU