Slot14!15!16 Libraries
Slot14!15!16 Libraries
[PFC] Libraries 1
CON
1 What is library in C?
2 Standard (stdlib.h)
TENT
N T
3 Time (time.h)
TE
4 Math (math.h)
5 Character (ctype.h)
C ON
[PFC] Libraries 2
What is library in C?
• Many basic tasks are very hard for programming beginners.
• The standard C libraries include functions to perform
mathematical calculations, character analysis and character
manipulation…
• Library header files have the extension .h
• Library binary files are implemented in files with specific
filenames which are named by designers of tool suppliers
(you may not know their names) and they are linked to your
programs when they are compiled.
[PFC] Libraries 4
The Standard Library: stdlib.h
int abs(int) long labs(long) Get absolute value of integral number
void exit(int code) Force the program terminating
int system(const char* programName) Request a program to execute
int rand(void) int srand(unsigned int seed)
Get a random integer in [0...RAND_MAX]
In Codeblocks (RAND_MAX=0x7FFF), start up the soft random mechanism
Functions for dynamic memory allocating
They are presented in the previous lecture
char* itoa(int num, char* result, int base)
char* ltoa(long num, char* result, int base)
Convert integral number to ASCII string
int atoi(const char*) long atol(const char*) double atof(const char*)
[PFC] Libraries 8
The Time Library: time.h
• Date and time information is presented in computer
using an integral number. It is usually the data type
long.
• A clock tick is the unit by which processor time is
measured and is returned by 'clock'.
• CLOCKS_PER_SEC: Number of clock ticks per
second. A constant is defined in time.h (in
Codeblocks, CLOCKS_PER_SEC = 1000 means that
1 clock tick = 1 milisecond).
• 2 data type are defined in the library time.h:
−time_t : (in Codeblocks: typedef long time_t;)
−clock_t: (in Codeblocks: typedef long clock_t;)
[PFC] Libraries 9
time.h # Functions
time_t time (time_t *tptr);
Returns the current calendar time and this time is stored in it’s parameter.
[PFC] Libraries 10
/* time_demo.c */
/* Evaluate time cost of 1000000000 mathematic operations */
#include <stdio.h>
#include <time.h>
int main() {
int i; int n=1; double x=1.5;
Example
/* Use time_t data type */
time_t t1 = time(NULL); /* Get current time */
for (i=0; i<1000000000; i++) x = x+1;
time_t t2 = time(NULL); /* Get current time */
double dt = difftime(t2, t1);
printf("\nCost of 1 billion real number adding operations: %lf
sec\n", dt);
t1 = time(NULL); /* Get current time */
for (i=0; i<1000000000; i++) n = n+1;
t2 = time(NULL); /* Get current time */
dt = difftime(t2, t1);
printf("\nCost of 1 billion integral number adding operations:
%lf sec\n", dt);
/* Use clock_t data type */
n = 1;
clock_t ct1 = clock(); /* Get current time */
for (i=0; i<1000000000; i++) n = n+1;
clock_t ct2 = clock(); /* Get current time */
printf("\nCost of 1 billion integral number adding operations:
%ld ticks\n", ct2 - ct1);
printf("\nor %lf secs\n", ((double)(ct2 - ct1)/CLOCKS_PER_SEC));
getchar();
}
[PFC] Libraries 11
math.h
[PFC] Libraries 12
The Math Library # Constants
#define M_E 2.7182818284590452354
#define M_LOG2E 1.4426950408889634074
#define M_LOG10E 0.43429448190325182765
#define M_LN2 0.69314718055994530942
#define M_LN10 2.30258509299404568402
#define M_PI 3.14159265358979323846
#define M_PI_2 1.57079632679489661923
#define M_PI_4 0.78539816339744830962
#define M_1_PI 0.31830988618379067154
#define M_2_PI 0.63661977236758134308
#define M_2_SQRTPI 1.12837916709551257390
#define M_SQRT2 1.41421356237309504880
#define M_SQRT1_2 0.70710678118654752440
[PFC] Libraries 13
The Math Library # Functions
Functions Description
double fabs(double) Compute absolute value
float fabsf(float) double v = abs(-5.5); // v = 5.5
double floor(double) Round down value
float floorf(float) double v = floor(16.7); // v = 16.0
double ceil(double) Round up value
float ceilf(float) double v = ceil(12.1); // v = 13.0
double round(double) Round to nearest
float roundf(float) double v1 = round(1.1); // v1 = 1.0
double v2 = round(1.6); // v2 = 2.0
double trunc(double) Truncate value
float truncf(float) double v = round(124.9); // v = 124.0
long double truncl(long double)
double sqrt(double) Compute square root
float sqrtf(float) double v = sqrt(15);
long double sqrtl(long double)
// v = 4.24264068711928514640506617262
[PFC] Libraries 14
The Math Library # Functions
Functions Description
sin, cos, tan, asin, acos, atan Trigonometric functions
double pow(double base, Compute absolute value
double exponent) double v = abs(-5.5); // v = 5.5
float powf(float base,
float exponent)
long double powl(long double base,
long double exponent)
double log(double) Round down value
float logf(float) double v = floor(16.7); // v = 16.0
long double logl(long double)
double exp(double) Round up value
float expf(float) double v = ceil(12.1); // v = 13.0
long double expl(long double)
[PFC] Libraries 15
/* math_demo.c */
#include <stdio.h>
#include <math.h>
int main() {
double x = 15.3, y =-2.6;
Example
printf("floor : %lf, %lf\n", floor(x), floor(y));
printf("ceil : %lf, %lf\n", ceil(x), ceil(y));
printf("round : %lf, %lf\n", round(x), round(y));
printf("trunc : %lf, %lf\n", trunc(x), trunc(y));
printf("sqrt : %lf\n", sqrt(x));
printf("pow - x^y: %lf\n", pow(x,y));
printf("exp - e^x: %lf\n", exp(x));
printf("log(x) : %lf\n", log(x));
printf("log2(x) : %lf\n", log(x) / log(2));
getchar();
}
[PFC] Libraries 16
ctype.h
[PFC] Libraries 17
The Character Library: ctype.h
• int isalnum(int c); alpha :
alphabet
• int isalpha(int c); num :
numeric/number
• int iscntrl(int c); cntrl :
control
• int isdigit(int c); print :
printable
• int isgraph(int c); punct :
punctuation characters
• int islower(int c); (ký tự phân cách)
• xdigit: hexadecimal digit
int isprint(int c);
• int ispunct(int c);
• int isspace(int c);
• int isupper(int c);
• int isxdigit(int c);
• int tolower(int c);
• int toupper(int c);
[PFC] Libraries 18
Input and validation
formatted output
[PFC] Libraries 19
Types of Input
Unbuffered Input User Device var Program
[PFC] Libraries 21
The getchar() function
• getchar() retrieves a single character from the
standard input stream buffer without translating the
input. Prototype: int getchar(void);
• getchar returns either the character code for the
retrieved character or EOF.
(EOF = -1, Ctrl-Z in Windows, Ctrl-D in Unix)
#include <stdio.h> Copy, Paste, compile
int main() { and run the program
char c;
with input: Ctrl + Z
printf("Input a character:");
c = getchar();
printf("Code inputted: %d\n",
c);
getchar();
} Libraries
[PFC] 22
getchar() # Clearing the buffer
• When the buffer input is used, in some cases, you may not
get successfully data for a variable because some
characters are remained in the keyboard buffer. How to
remove them?
/* clear empties input buffer */
void clear(void) {
while(getchar() != '\n');
}
• In some tools, the function fflush(stdin) is implemented
for this purpose (in stdio.h header file).
• To assure that a program always receives new character
data. Make clear the keyboard buffer before the operation
of accepting a character (or a string).
[PFC] Libraries 23
getchar() # Example @ Mistake
Copy, paste, compile and run the program
#include <stdio.h>
int main() {
char c1, c2;
printf("Input the 1st character:"); Keyboard Buffer
scanf("%c", &c1); A 01000001
printf("Input the 2st character:");
00001101
c2 = getchar(); Enter
printf("c1=%c, ASCII:%d\n", c1, c1); 00001010
printf("c2=%c, ASCII:%d\n", c2, c2);
c1 01000001
getchar();
} c2 00001010
The problem is that after user presses 'A' and ENTER (2 code: 13, 10),
ASCII codes of them are put into the keyboard buffer. The function
scanf(...) will get 'A' to c1. The remaining codes, 13 and 10, are
interpreted to the character '\n' – code 10 only, to c2 by the function
getchar(). So, you can not get a new character for c2.
[PFC] Libraries 24
getchar() # Example @ Solution
Copy, paste, compile and run the program
#include <stdio.h>
#include <stdlib.h>
int main() {
char c1, c2;
printf("Input a character:");
fflush(stdin);
c1 = getchar();
printf("Input a character:");
fflush(stdin);
c2 = getchar();
printf("c1: %c, ASCI code: %d, %o, %X\n",c1,c1,c1,c1);
printf("c2: %c, ASCI code: %d, %o, %X\n",c2,c2,c2,c2);
system("pause"); The function system("commandName"), is
} prototyped in stdlib.h, allows calling a
program stored in system file or an OS
command.
[PFC] Libraries 25
getchar() # Clears keyboard buffer
Copy, paste, compile and run the program
[PFC] Libraries 26
scanf() function
[PFC] Libraries 27
The scanf(…) function
• scanf retrieves data values from the standard input
stream buffer under format control.
scanf(format string, &identifier, ...)
• scanf extracts data values from the standard input
stream buffer until scanf has
−Interpreted and processed the entire format string.
−Found a character that doesn’t meet the next
conversion specification in the format string, in which
case scanf leaves the offending (phạm lỗi) character
in the buffer, or emptied the buffer, in which case
scanf waits until the user adds more data values.
[PFC] Libraries 28
Conversion Specifiers
Specifier Input value Use with
%c character char
%*c character Remove one character in the input buffer
%d decimal char, int, short, long, long long
%u decimal unsigned int, char, int, short, long, long long
%o octal unsigned int, char, int, short, long, long long
%x %X hexadecimal unsigned int, char, int, short, long, long long
%ld long long
%f float float
%lf double double
%llf long double long double
Data from the keyboard are passed to the buffer as characters (ASCII
codes). So, conversion specifiers are instructions that specifying how to
converse character data to typed-data. If a specifier does not match the
data type of a variable, the conversion is incorrect.
[PFC] Libraries 29
Conversion Specifiers # Example
[PFC] Libraries 30
Default Separators
If a input value is number lead by a whitespace, scanf treats
the whitespace as a separator (The whitespace characters
include newline, horizontal tab, form feed – page-breaking
ASCII, vertical tab and space characters).
[PFC] Libraries 31
User-Defined Separators
User can specify the
character for separating
input data.
User-define separators
will override default
separators.
[PFC] Libraries 32
Using %*c for removing a character
Input: 70 ENTER
'\n'
[PFC] Libraries 33
Number of data fields are inputted
scanf returns the number of addresses successfully
filled or EOF. A return value of
• 0 indicates that scanf did not fill any address
• 1 indicates that scanf filled the first address successfully
• 2 indicates that scanf filled the first and second
addresses successfully
• ...
• EOF (-1) indicates that scanf did not fill any address
AND encountered an end of data character.
[PFC] Libraries 35
Input Validation
• We can't predict how the user will input the data
values: whether the user will enter them as
requested or not.
• One user may make a mistake.
• Another user may simply try to break the program.
• The program should have code for trapping all
erroneous input, which includes:
−invalid characters
−trailing characters
−out-of-range input
−incorrect number of input fields
[PFC] Libraries 36
Input Validation # Example
The following function will ensure that inputted integer must be in the range [min, max] and
no invalid characters or trailing character following inputted digits (EXCEPT the ENTER key)
[PFC] Libraries 37
Formatted Output
[PFC] Libraries 38
Formatted Output
• Standard output is buffered.
• The standard output buffer empties to the
standard output device whenever the buffer
receives a newline character or the buffer is full.
• Buffering enables a program to continue executing
without waiting for the output device to finish
displaying the most recently received characters.
• The library stdio.h containing functions for print
out data:
−putchar(int): character
−printf(format_string, varList): list of data
[PFC] Libraries 39
The function putchar(int)
• putchar writes the character received to the standard
output stream buffer and returns the character written
or EOF if an error occurred.
• Prototype: int putchar(int);
• For example: putchar('a');
[PFC] Libraries 40
The function printf(…)
• printf sends data under format control to the standard
output stream buffer and returns the number of characters
sent.
• Syntax: printf(format string, value, ..., value)
[PFC] Libraries 41
Format String
Between the % and the conversion character,
there may be
% flags width . precision size conversion_character
flags
- prescribes left justification of the converted value in its
field
0 pads the field width with leading zeros
size identifies the size of data type of the value passed.
[PFC] Libraries 42
Conversion Specifiers
[PFC] Libraries 43
Example 1
[PFC] Libraries 44
Example 2
[PFC] Libraries 45