COM 101 B LECTURE 4 INPUT OUTPUT ASST

COM 101 B LECTURE 4: INPUT & OUTPUT ASST. PROF. DR. HACER YALIM KELEŞ REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST PUBLISHING CO. , 1992

• C does not provide language constructs for input/output operations. • However, ANSI C has defined a rich standard I/O library: • a set of functions designed to provide a standard I/O system for C programs. • We will study some subset of this library: • • printf: used for output operations scanf: used for input operations • A program that uses I/O functions needs to include <stdio. h>: • #include <stdio. h> REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST PUBLISHING CO. , 1992

Example: printf( «%c» , ’C’); results in: >C • Here > represent the output prompt. REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST PUBLISHING CO. , 1992

PRINTF FUNCTION The printf statement: int i = 1; printf( «%dn» , 2*i); results in: >2 The printf statement: float r = 100. 0; printf( «n%ft%e» , r, 100. 0); results in: >100. 000000 1. 000000 e+002 REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST PUBLISHING CO. , 1992

PRINTF FUNCTION • The printf statement: • • float c = -11. 428572; printf( «%f Cent = %f %sn» , c, 1. 8*c+32, «Fahr» ); >-11. 428572 Cent = 11. 428571 Fahr REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST PUBLISHING CO. , 1992

PRINTF FUNCTION • The blank characters in the control string are significant: printf( « 1 2 3 4 >1 2 3 4 endn» ); end REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST PUBLISHING CO. , 1992

FORMAT SPECIFIERS REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST PUBLISHING CO. , 1992

SCANF FUNCTION • It is the input analog of the printf function • scanf(control string, arg 1, arg 2, . . . ); • The control string contains conversion specifications. • The scanf function reads one data item from the input corresponding to each argument other than the control string • skipping the whitespaces including newlines to find the next data item, and returns the total number of arguments that are successfully read. • It returns EOF (End Of File) when the end of the input is reached. REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST PUBLISHING CO. , 1992

CONVERSION CONTROL CHARS REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST PUBLISHING CO. , 1992

SCANF FUNCTION Example: int i; float f 1, f 2; char c 1, c 2; Input: 10 1. 0 e 1 10. 0 pc Statement: scanf( «%d %f %e %c %c» , &i, &f 1, &f 2, &c 1, &c 2); results in: i = 10; f 1=10. 000000; f 2=10. 000000; c 1=‘p’; c 2=‘c’ REFERENCE: “PROGRAMMING IN ANSI C”, KUMAR & AGRAWAL, WEST PUBLISHING CO. , 1992
- Slides: 10