80 likes | 227 Views
Standard I/O Functions - Overview. Standard I/O refers to displaying output to screen and getting input from keyboard. A set of functions available from standard library are as follows: Standard Output : printf(), putchar(), puts() Standard Input : scanf(), getchar(), gets();
E N D
Standard I/O Functions - Overview Standard I/O refers to displaying output to screen and getting input from keyboard. A set of functions available from standard library are as follows: Standard Output : printf(), putchar(), puts() Standard Input : scanf(), getchar(), gets(); In order to use these functions, one must include the stdio.h header file into their source file using preprocessing directive: #include<stdio.h>
Standard I/O Functions – printf() The printf function call has the following general syntax printf (FormatControlString, PrintList); FormatControlStringis a string that may consist of ordinary characters, escape sequences and format specifiers. PrintList is any number of constants, variables, expressions and function calls separated by commas. Simple example with 1 element in the PrintList: int my_age = 28; printf(“My age is %d\n”, my_age); Output: My age is 28
Standard I/O Functions – printf() FormatControlString printf(“My age is %d \n ”, my_age); Escape sequence: \n signifies newline Characters Format specifiers: %d indicate the data type is of decimal integer PrintList consist of 1 variable
Standard I/O Functions – printf() More complex example with multiple elements in PrintList : int radius = 2; float area; printf(“Circle area is %8.4f x %d x %d = %8.4f\n”, 3.1428, radius, radius, area = 3.1428*radius*radius); Output: Circle area is 3.1428 x 2 x 2 = 12.5712
Standard I/O Functions – printf() More complex example : printf(“Circle area is %8.4f x %d x %d = %8.4f\n”, 3.1428, radius, radius, area = 3.1428*radius*radius); constant Format specifier for data type float 8.4 is the display formatting setting (discuss later) Arithmetic Expression
The result returned by function sqrt() is displayed Standard I/O Functions – printf() Example with function call in PrintList : printf(“Square root of %d = %8.4f\n”, 2, sqrt(2)); Output: Square root of 2 = 1.4142
Standard I/O Functions – printf() Here are a list of most frequent used format specifiers %d – decimal representation of integer number (char, short, int) %ld – decimal representation of long integer (long) %x – Hexadecimal representation of integer and floating- point number (lowercase) %X – Hexadecimal representation of integer and floating- point number (uppercase)
Standard I/O Functions – printf() %c – ASCII character representation of integer (char) %s – string literal (char[],”hello!”) %f – floating point number in conventional format (float) %lf –long floating point number in conventional format (double, long double) %e(%E) – floating point number in scientific format (float) %le(%lE) – long floating point number in scientific format (double, long double)