The C standard library is a collection of all standard-compliant header files, as well as commonly used library implementations such as I/O input and output and string control. Unlike programming languages ​​such as COBOL, Fortran, and PL/I, embedded keywords are not included in C tasks, so almost all C programs are created by functions of standard libraries.
The name and characteristics of each function are written as a computer file. This file is called a header file, but the actual function implementation is stored in the function library file. The naming and domain of header files is very common, but the organization of the library will vary from compiler to compiler. Standard libraries are usually included with the compiler. Because the C compiler often provides some additional non-ANSI C function functionality, a standard library attached to a particular compiler is not compatible with other different compilers.
This article introduces the usage of several commonly used standard C functions, mainly introduces stdio (standard input and output), math (digital function library), time (time function library), stdlib (standard function library) string (standard string function) and so on.
1.1 stdio.hStandard input/output function, stdio is standard input/output. The file operation related API is described in a separate chapter.
#include "stdio.h"
Char getchar(void); // Enter one character from the console
Int putchar(int c); // The console outputs a character
Char *gets(char *s); // enter a string in the console
Int puts(const char *s); // The console outputs a string
Int printf(const char *format, . . .); // console formatted output
Int scanf(const char *format, . . .); // console formatted input
Int sprintf(char *s, const char *format, . . .); // string formatted output
Int sscanf(const char *s, const char *format, . . .); // string formatted input
1.1.4 sprintf and sscanf
Applicable to the formatted input/output of the string version, the target is not the console, but a string. These two functions are very useful.
Format a string with sprintf, for example,
[cpp] view plain copychar buf [256];
Sprintf (buf, “Name: %s, Age: %d, Height: %.2fâ€, “LiMingâ€, 30, 1.68);
This code formats the target buf as: Name: LiMing, Age 30, Height: 1.68
Use sscanf to extract fixed fields from a formatted string, similar to the usage of scanf, requiring strict matching in format. The following code provides the value of the year, month, and day from the characters.
[cpp] view plain copychar* src = â€2014-12-11â€;
Int year, month, day;
Int n = sscanf ( src,
"%d-%d-%d",
&year, &month, &day);
If( n == 3)
{
// successfully extracted all the fields
}
1.2 math.hProvides a series of mathematically related functions such as trigonometric functions, exponents/logs, power/root numbers, and so on.
#include 《math.h》
Double abs(double x); // take absolute value
Double cos(double x); // cosine cos, the argument is the radians value
Double sin(double x); // sine sin, argument is radians
Double tan(double x); // tangent tan, argument is radians
Double ceil(double x); // round up, ie the smallest integer not less than x
Double floor(double x); // round down, ie the largest integer not greater than x
Double exp(double x); // ask for ex
Double log(double x); // ln(x), the base e logarithm
Double log10(double x); // lg(x), base 10 logarithm
Double pow(double x, double y); // power xy
Double sqrt(double x); // find the square root x1/2
It should be added that almost all of the functions listed here have at least two versions, which are double and float. E.g,
[cpp] view plain copydouble sqrt(double x);
Float sqrt(float x);
The following code compile error,
[cpp] view plain copydouble result = sqrt (16); // compile error
Why are there compilation errors? Because the literal constant 16 is of type int, both sqrt(float) and sqrt(double) are matched when matching a function, and int can be implicitly converted to float and double. Must be shown to force the argument to double or float.
If you want to call the sqrt function on an integer, you must explicitly convert it to a double or float, for example,
[cpp] view plain copydouble result = sqrt ((double)16); // OK
or
Float result = sqrt ((float)16); // OK
1.2.1 abs to find the absolute value
E.g,
[cpp] view plain copydouble a = abs ( -12.34);
1.2.2 cos/sin/tan trigonometric function
Its units are all radians. E.g,
[cpp] view plain copy#define PI 3.1415926535898
Double ret = sin ( PI / 2); // sin (pi/2) should result in 1
1.2.3 ceil / floor rounding
Used to round up/down. E.g,
[cpp] view plain copydouble ci = ceil ( 12.87 ); // +13
Double fi = floor(12.87); // +12
Ci = ceil ( -12.87 ); // -12
Fi = floor( -12.87); // -13
1.2.4 exp / log / log10 / pow / sqrt index / log / power / square root
Click to view this section, Chapter 16
1.3 time.hTime/date related functions are provided in time.h. Only a few of the commonly used functions are listed here.
#include 《time.h》
Struct tm *localtime(const time_t *tod); // When "second value" is converted to "year, month, day, hour, minute and second"
Time_t mktime(struct tm *tptr); // Convert "year, month, day, hour, minute, and second" to "second"
Time_t time(time_t *tod); // get the current time
Among them, you need to introduce the two types time_t and struct tm.
1.3.1 time_t
Time_t is a typedef type. Currently, the time_t type is an integer type on various operating systems.
Typedef long time_t;
This similar definition can be considered int type in various situations. Of course, insurance can also be explicitly forced to change. Its unit is seconds.
[cpp] view plain copytime_t start = 1000;
Time_t end = 1020;
Printf("time eclipse: %d seconds !", (int)(end - start));
1.3.2 struct tm
Tm is a structure, its definition is,
Struct tm
{
Int tm_sec; /* seconds after the minute - [0,59] */
Int tm_min; /* minutes after the hour - [0,59] */
Int tm_hour; /* hours since midnight - [0,23] */
Int tm_mday; /* day of the month - [1,31] */
Int tm_mon; /* months since January - [0,11] */
Int tm_year; /* years since 1900 */
Int tm_wday; /* days since Sunday - [0,6] */
Int tm_yday; /* days since January 1 - [0,365] */
};
It is used to represent date/time and consists of several fields: year, month, day, hour, minute, second, weekday and yearday. among them,
Year: Starting from 1900, tm_year = 114 means year 1900 + 114 = 2014
Month: Range is [0,11], tm_mon = 11 means month 12
Day: The range is [1, 31], and tm_mday = 24 indicates the 24th day of the month.
Time: The range is [0, 23], tm_hour = 13 means 13 pm
Points: The range is [0,59], tm_min = 40 means the 40th minute
Seconds: the range is [0,59], tm_sec = 40 means the 40th second
Tm_wday: The range is [0,6], Sunday is 0, and Monday is 1. . . Saturday is 6
Tm_yday: The range is [0,365], tm_yday=299, indicating the 300th day of the year
When both tm_min and tm_sec are 0, it represents the hour. Such as 12:00:00.
For example, 2014-12-11 11:47:12 this time can be assigned with the following code:
[cpp] view plain copytm info;
Info.tm_year = 2014 - 1900; // 2014
Info.tm_mon = 12 - 1; // December
Info.tm_mday = 11; // 11th
Info.tm_hour = 11; // 11 o'clock
Info.tm_min = 47; // 47 points
Info.tm_sec = 12; // 12 points
1.3.3 time to get the current time of the system
The time function can get the current time of the system, and the return value is a second value. E.g,
[cpp] view plain copytime_t now = time (NULL);
Why can an integer second value represent the current time? It is stipulated that the time function returns the time difference from the time point of 1970-1-1 00:00:00 to the current time. It is a relatively large integer, for example 1418270153 represents the moment 2014-12-11 11:55:53.
When using the time function, you can calculate how much time the program runs, such as the following code:
[cpp] view plain copytime_t start = time (NULL);
. . . DoSomething. . .
Time_t end = time (NULL);
Printf("Time cost : %d seconds", end - start );
Of course, this DoSomething has to run for quite some time, because the time granularity is large, and the return is the second value. If your DoSomething only takes a few milliseconds, then you can't measure it at all. However, you can quantify multiple times, compare, and do DoSomething continuously for 10,000 times, see the total time required, and then average the time required for a single time.
[cpp] view plain copytime_t start = time (NULL);
For( int i=0; i" 10000; i++)
{
. . . DoSomething. . .
}
Time_t end = time (NULL);
Int avg = (end - start ) / 10000;
1.3.4 localtime () to get the year, month, day, hour, minute, second
Although it is convenient to use a time_t integer to represent the current system time, sometimes it is hoped that it can be converted into a form of year, month, day, minute, and second. After all, the naked eye cannot directly see which date a time_t value is.
The localtime function can convert the time represented by time_t into year, month, day, hour, minute, and second, for example,
[cpp] view plain copytime_t t = time(NULL);
Tm info = *localtime(&t);
Printf("%04d-%2d-%02d %02d:%02d:%02d",
Info.tm_year + 1900,
Info.tm_mon + 1,
Info.tm_mday,
Info.tm_hour,
Info.tm_min,
Info.tm_sec);
The return value of localtime is tm* type, and the content should be saved with a tm variable.
In fact, it is more convenient to use time_t to record time. The date and time information is expressed by only one integer (4 bytes). When saving and transferring, you should try to use the time_t type. Only in the final display, use localtime to convert into human yyyy-mm-dd HH:MM:SS format.
1.3.5 mktime construction time
When the year, month, day, minute, and second information is known, it can be converted to time_t value by mktime. For example, turn 2014-12-11 11:47:12 into a time_t value,
Click to view this section, Chapter 16
1.4 stdlib.hThis section will introduce the APIs provided in stdlib.h. Here are a few of the main functions:
#include "stdlib.h"
Double atof(const char *s);
Int atoi(const char *s);
Int rand(void);
Void srand(unsigned int seed);
Int system(const char *s);
1.4.1 atoi / atof string into a number
E.g,
[cpp] view plain copyint n = atoi("1280");
Double f = atof("12.80");
In fact, you can use sscanf to do the same thing, for example,
[cpp] view plain copyint n;
Double f;
Sscanf("1280", "%d", &n);
Sscanf("12.80", "%f", &f);
In contrast, using atoi and atof is a bit more concise.
1.4.2 rand / srand random number generation
In an application scenario involving "random events" such as lottery, lottery, etc., a random number generation function is required. Because there is no randomness and contingency in the computer, it is actually a difficult thing to create a random number. To be truly random numbers, you need to purchase very expensive hardware that uses some natural science rules to generate random numbers. Because of the high price, professional random number generators are only used for professional purposes. The "pseudo-random number" generation function that we can introduce here is suitable for ordinary PCs, and it is possible to generate approximately random data.
The rand function is used to generate a random number, which returns an integer. Test the following code:
[cpp] view plain copyfor(int i=0; i"10; i++)
{
Printf("%d", rand());
}
The console outputs 10 completely irregular numbers, so it is called a random number because it is completely irregular. Here, for the convenience of display, only 10 random numbers are generated. In fact, it can be changed to 1000 times and 10,000 times. It will be found that it is indeed disorderly and completely irregular.
So why is it a "pseudo-random number"? Explain that it does not really implement "random". You can verify this by running the same program several times and you will find that the result of each program run output is the same sequence of numbers. For example, when running the program for the first time, 10 random numbers such as 13435 31833 5075 19863 30565 11677 1339 4096 31105 9088 are output, and when the shutdown program is run again, the 10 random numbers output are still the 10 numbers.
To solve this problem, the srand function is provided in stdlib.h. The srand function is used to set a seed for the program. When the seeds are different, the sequence of random numbers generated by the program is different. Srand only needs to be set once at the beginning of the program, for example, it can be run once at the beginning of the main() function. How is the seed determined? To ensure that the value of this seed is different each time the program runs, it is generally taken as the seed.
[cpp] view plain copyvoid main()
{
Srand (time (NULL));
. . . Do something else. . .
}
The time returned by time(NULL) is different each time the program runs, so srand uses a different seed each time. When you call rand() in your program to generate a random number, you will find that the sequence of random numbers generated by each program run is different.
How to use the rand function in practical applications? For example, there is a lottery ticket called "Seven Stars", and the winning number generated each time is 7 random numbers between 0 and 9. You can use rand to randomly generate a note number.
[cpp] view plain copyvoid main()
{
Srand (time (NULL));
Int code[7]; // One note number is 7 digits
For(int i=0; i"7; i++)
{
Int r = rand () % 10; // modulo so that each number is between 0 and 9
Code[i] = r;
}
}
Note that you usually specify an interval for the random number generated by rand().
Generate a random number between [100, 120],
[cpp] view plain copyint r = 100 + rand () % 20;
Generate a random fraction of the interval [0,1],
Double r = rand()/ (double)RAND_MAX;
Among them, RAND_MAX is defined as 32767 under VC, and may be other values ​​under other operating systems.
Example: Given 10 numbers, ask for 5 numbers randomly selected from each.
Idea: First, randomly select one from 10 numbers, then pick one from the remaining nine, and then pick one from the remaining eight. . . . . .
Design: Use a flags array to indicate which number has been selected. For example, flags[3] = 1 indicates that the 4th number has been selected, and flags[9]=0 indicates that the 10th number is not selected.
Click to view this section, Chapter 16
1.4.3 system call system command line
Use the system function to call the system command line, you can execute the DOS command line under Windows, and the SHELL command line under Linux. For example, delete the d:\aaa.pdf file.
System ("del /F /Q d:\\aaa.pdf");
In fact, in principle, it is not limited to DOS commands, so the command line can be run. For example, calling a browser to open a website,
[cpp] view plain copysystem ("explorer http://");
1.5 string.hA system memory operation function and a string manipulation function are provided in string.h. Before you study this section, be sure to learn the meaning of strings in Chapter 15.
#include 《string.h》
Char *strcat(char *s1, const char *s2); // splicing string
Char *strchr(char *s, int c); // find characters
Int strcmp(const char *s1, const char *s2); // string comparison
Char *strcpy(char *s1, const char *s2); // copy the string
Char *strstr(char *s1, const char *s2); // find the substring
Size_t strlen(const char *s); // calculate length
Int memcmp(const void *s1, const void *s2, size_t n); //by memory comparison
Void *memcpy(void *s1, const void *s2, size_t n); // by memory copy
Void *memmove(void *s1, const void *s2, size_t n); // move data
Void *memset(void *s, int c, size_t n); // fill memory by byte
1.5.1 strcpy copy string
Strcpy(a,b) is used to copy the string b to the target buffer.
Such as,
[cpp] view plain copychar buf[128];
Strcpy(buf, "LiMing"); // copy the target buffer content to "LiMing"
1.5.2 strcat splicing string
Strcat(a,b) is used to stitch the string b to the string a, that is, to copy the string to the end of the target string. This function requires the target buffer to be large enough.
[cpp] view plain copy#include "string.h"
Void main()
{
Char a [128] = "hello";
Char b [] = "world";
Strcat(a, b); // The result of goal a is "helloworld"
}
1.5.3 strcmp comparison string
The meaning of string comparisons is covered in Chapter 15. Strcmp(a,b) is used to compare strings. When returning to 0, it means completely equal. When it is less than 0, it means a "b. When it is greater than 0, it means a"b.
[cpp] view plain copyint ret = strcmp("Jack", "Jacky"); // Return value ret=-1, indicating "Jack" ""Jacky"
1.5.4 strlen for string length
When the string is lengthed, the terminator '\0' is not counted. E.g,
[cpp] view plain copyint n = strlen("LiMing"); // return length n is 6
1.5.5 strchr lookup characters
Strchr(s, c) is used to look up the character c in the string s and return the first matching position. Its return value is char* type, indicating the location of the match,
[cpp] view plain copychar* s = "LiMing";
Char* p = strchr(s, 'M'); // return value p points to the address of the character 'M'
If(p!= NULL)
{
Printf("find: %s ", p);
}
1.5.6 strstr finds a substring
Click to view this section, Chapter 16
1.5.7 memset memory fill
[cpp] view plain copymemset(s, c, n) is used to add n identical characters c to the target buffer s, for example,
Unsigned char buf[128];
Memset(buf, 0, sizeof(buf)); // all padded to 0
Memset(buf, 0xFF, 128); // all padded to 0xFF
Memset(buf, 0x55, 100); // The first 100 bytes are filled with 0x55
Memset(buf+100, 0x77, 10); // 100..109 is padded to 0x77
1.5.8 memcpy memory copy
Click to view this section, Chapter 16
1.5.9 memcmp memory comparison
Click to view this section, Chapter 16
Among them, the comparison of a and b is easy to get results, but what is the comparison between a and c? Since it is converted to unsigned char and then compared, so c "a.
1.5.10 memmove mobile data
Memmove(dst, src, n) is used to move data in memory, moving the n bytes starting at src to the dst position. The power of this function is that it allows src and dst to overlap.
For example, with this function we can implement inserting characters into a string. When inserting a string, if all characters after the insertion point are moved back,
Click to view this section, Chapter 16
Click to view this section, Chapter 16
1.6 stdarg.hThe interface in stdarg.h is used to implement the ellipsis parameter. It has been pointed out in the function that the function parameter has a special form, that is, it does not specify the number and type, and is directly represented by an ellipsis.
Void test (..)
When the parameter is an ellipsis, you can enter any number of parameters, and the type of the parameter is not limited. We observe the prototype of the printf function and find that it uses the ellipsis parameter.
Int printf(const char *format, . . . )
The first argument to printf is a string type that is used to pass format arguments, and the following ellipsis can pass 0..N arguments. This flexible method of transmission is used in some special occasions. The following points out an application requirement and gives its implementation.
Requirement: Customize a function for log output, automatically add date period information and log level when outputting, and its prototype requirement is this form.
Void log(int level, const char* fmt, . . . )
Where level is the log level: level=0, ERR is displayed, level=1 is displayed: WRN, level=2 displays INF, level=3 displays DBG.
At the time of the call, it is required to use the format control character to control the output similar to printf, and the prefix is ​​displayed by date:
Log(0, "My name is %s, I'm %d years old.", "Jennifer", 30);
This requirement is actually to implement a custom print function.
[cpp] view plain copy#include "stdio.h"
#include 《string.h》
#include "stdarg.h"
Void log(int level, const char* fmt, . . .
{
// print log level
Const char* token = â€DBGâ€;
Switch(level)
{
Case 0: token = "ERR"; break;
Case 1: token = "WRN"; break;
Case 2: token = â€INFâ€; break;
Case 3: token = â€DBGâ€; break;
}
Printf("[ %s ] ", token);
/ / Format the ellipsis parameter into a string
Char buf[512];
Va_list args;
Va_start(args, fmt);
Vsprintf(buf, fmt, args);
Va_end(args);
Printf(buf);
}
Int main()
{
Log(2, "Name: %s, Age: %d.", "LiMing", 30);
Return 0;
}
The core processing of the ellipsis parameter is these lines of code:
[cpp] view plain copyva_list args;
Va_start(args, fmt);
. . . The parameters have been taken in args here. . .
Va_end(args);
The functions that can take va_list as arguments are vsprintf, vprintf, vfprintf, whose prototype is:
Int vprintf(const char *format, va_list ap); // output to the console
Int vsprintf(char *s, const char *format, va_list ap); // output to string buffer
Int vfprintf(FILE *stream, const char *format, va_list ap); // output to file stream
TPU Cutting Machine Accessories
Cutting Head Parts suitable for Screen Protector Cutting Machine.
The Cutting Blade can be used to cut Hydrogel Screen Protector, Back Film, Watch Screen Protector, etc. The quality of the Accessories For Cutter is higher than that of stainless steel, sharp and durable, and can be cut for a long time. In addition, the blade is protected by a plastic cover to avoid scratching your fingers.
Cutting Blade Parts For Screen Protector Cutter,Cutting Tip For Screen Protector Cutting Machine,Mobile Phone Screen Protection Cardboard Scraper Tool,Scraper For Film Cutting Machine
Shenzhen TUOLI Electronic Technology Co., Ltd. , https://www.hydrogelprotector.com