Wednesday, April 2, 2008

Format Specifiers and Escape sequences

Format Specifiers in I/O Operations

Functions like printf( ) and scanf( ) are used for console I/O operations. The first argument these functions take is a string and later on any number of variables as arguments. In the first argument you have to inform how to interpret the variables coming later on. as int? or char? or float? ….

E.g 1. printf(“Amount = %d” , x );

Explanation:

%d = Format specifier for an int type

x = variable

read x as an int . If value of x is 100 then the output is

Amount = 100

E.g 2. printf(“You entered %c” , ch );

Explanation:

%c = Format specifier for char type

ch = variable

read ch as a char . If value of ch is ‘A’ then the output is

You entered A

E.g 3. printf(“a = %f b = %f” , a , b ) ;

Explanation:

%f = Format specifier for float type

a , b = variables

read a ,b as floats

E.g 4. printf(“p = %d q = %c r = %f ” , p . q , r ) ;

Explanation:

read p as int , q as char , r as float


Data Type

Format Specifier

char

%c

int

%d or %I

float

%f

double

%lf

unsigned char

%uc

unsigned int

%u

long int

%ld

unsigned long int

%lu

long double

%Lf

float as ¨exponential or scientific notation

%e or %E

Octal format

%o

Hexadecimal format

%x or %X

char * as a string

%s

Note : If you want to print % you will have to give it as %%

Escape Sequences

A combination of backslash and a character like ‘\n’ is treated as a single character constant, and is known as an escape sequence. It is interpreted with special meanings such as newline, tab, backspace etc.

Escape sequence

Interpretation

‘\n’

New line or line feed. Control returns to the first character of the next line

‘\t’

Horizontal tab

‘\v’

Vertical tab

‘\b’

Back Space

‘\r’

Carriage return. Control returns to the first character of the current line

‘\a’

Alert or bell or beep

‘\f’

form feed

‘\\’

print \

‘\”’

print “

‘\?’

print ?

‘\’’

print ‘

‘\nnn’ Backslash followed by octal digits

Octal number

‘\xnnn’ Backslash followed by x and hexadecimal digits

Hexadecimal number



Exponential or scientific notation :

A floating point number is expressed as characteristic mantissa format to the base 10

123456.6754 is expressed as 1.235e+5

0.0000012345 is expressed as 1.235e-6

No comments: