Home Backend Development C++ C, Essential Libraries

C, Essential Libraries

Jul 18, 2024 pm 10:47 PM

C, Essential Libraries

stdio.h

The stdio.h library in C provides functionalities for input and output operations. Here are some of the important functions provided by stdio.h with examples:

printf

  • Prints formatted output to the standard output (stdout).
  • Syntax: int printf(const char *format, ...)
#include <stdio.h>

int main() {
    printf("Hello, World!\n");  // Output: Hello, World!
    printf("Number: %d\n", 10); // Output: Number: 10
    return 0;
}
Copy after login

scanf

  • Reads formatted input from the standard input (stdin).
  • Syntax: int scanf(const char *format, ...)
#include <stdio.h>

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    printf("You entered: %d\n", num);
    return 0;
}
Copy after login

gets

  • Reads a line from stdin into the buffer pointed to by s until a newline character or EOF is encountered.
  • Syntax: char *gets(char *s)
#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    gets(str);
    printf("You entered: %s\n", str);
    return 0;
}
Copy after login

fgets

  • Reads a line from the specified stream and stores it into the string pointed to by s. Reading stops after an n-1 characters or a newline.
  • Syntax: char *fgets(char *s, int n, FILE *stream)
#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, 100, stdin);
    printf("You entered: %s\n", str);
    return 0;
}
Copy after login

putchar

  • Writes a character to the standard output (stdout).
  • Syntax: int putchar(int char)
#include <stdio.h>

int main() {
    putchar('A');  // Output: A
    putchar('\n');
    return 0;
}
Copy after login

getchar

  • Reads the next character from the standard input (stdin).
  • Syntax: int getchar(void)
#include <stdio.h>

int main() {
    int c;
    printf("Enter a character: ");
    c = getchar();
    printf("You entered: %c\n", c);
    return 0;
}
Copy after login

puts

  • Writes a string to the standard output (stdout) followed by a newline character.
  • Syntax: int puts(const char *s)
#include <stdio.h>

int main() {
    puts("Hello, World!");  // Output: Hello, World!
    return 0;
}
Copy after login

fputs

  • Writes a string to the specified stream.
  • Syntax: int fputs(const char *s, FILE *stream)
#include <stdio.h>

int main() {
    fputs("Hello, World!\n", stdout);  // Output: Hello, World!
    return 0;
}
Copy after login

stdlib.h

The stdlib.h library in C provides various utility functions for performing general-purpose operations, including memory allocation, process control, conversions, and searching/sorting. Here are some of the important functions provided by stdlib.h with examples:

malloc

  • Allocates a block of memory of a specified size.
  • Syntax: void *malloc(size_t size)
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr;
    int n = 5;
    arr = (int *)malloc(n * sizeof(int));  // Allocates memory for 5 integers
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    for (int i = 0; i < n; i++) {
        arr[i] = i + 1;
    }

    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);  // Output: 1 2 3 4 5
    }

    free(arr);  // Frees the allocated memory
    return 0;
}
Copy after login

calloc

  • Allocates a block of memory for an array of elements, initializing all bytes to zero.
  • Syntax: void *calloc(size_t num, size_t size)
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr;
    int n = 5;
    arr = (int *)calloc(n, sizeof(int));  // Allocates memory for 5 integers and initializes to zero
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);  // Output: 0 0 0 0 0
    }

    free(arr);  // Frees the allocated memory
    return 0;
}
Copy after login

realloc

  • Changes the size of a previously allocated memory block.
  • Syntax: void *realloc(void *ptr, size_t size)
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr;
    int n = 5;
    arr = (int *)malloc(n * sizeof(int));  // Allocates memory for 5 integers
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    for (int i = 0; i < n; i++) {
        arr[i] = i + 1;
    }

    n = 10;  // Resize the array to hold 10 integers
    arr = (int *)realloc(arr, n * sizeof(int));
    if (arr == NULL) {
        printf("Memory reallocation failed\n");
        return 1;
    }

    for (int i = 5; i < n; i++) {
        arr[i] = i + 1;
    }

    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);  // Output: 1 2 3 4 5 6 7 8 9 10
    }

    free(arr);  // Frees the allocated memory
    return 0;
}
Copy after login

free

  • Frees the previously allocated memory.
  • Syntax: void free(void *ptr)
#include <stdlib.h>

int main() {
    int *arr = (int *)malloc(5 * sizeof(int));
    // ... use the allocated memory ...
    free(arr);  // Frees the allocated memory
    return 0;
}
Copy after login

exit

  • Terminates the program.
  • Syntax: void exit(int status)
#include <stdio.h>
#include <stdlib.h>

int main() {
    printf("Exiting the program\n");
    exit(0);  // Exits the program with a status code of 0
    printf("This line will not be executed\n");
    return 0;
}
Copy after login

string.h

The string.h library in C provides functions for handling strings and performing various operations on them, such as copying, concatenation, comparison, and searching. Here are some of the important functions provided by string.h with examples:

strlen

  • Computes the length of a string.
  • Syntax: size_t strlen(const char *str)
#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "Hello, world!";
    printf("Length of the string: %zu\n", strlen(str));  // Output: Length of the string: 13
    return 0;
}
Copy after login

strcpy

  • Copies a string to another.
  • Syntax: char *strcpy(char *dest, const char *src)
#include <stdio.h>
#include <string.h>

int main() {
    char src[] = "Hello, world!";
    char dest[50];
    strcpy(dest, src);
    printf("Copied string: %s\n", dest);  // Output: Copied string: Hello, world!
    return 0;
}
Copy after login

strncpy

  • Copies a specified number of characters from a source string to a destination string.
  • Syntax: char *strncpy(char *dest, const char *src, size_t n)
#include <stdio.h>
#include <string.h>

int main() {
    char src[] = "Hello, world!";
    char dest[50];
    strncpy(dest, src, 5);
    dest[5] = '\0';  // Null-terminate the destination string
    printf("Copied string: %s\n", dest);  // Output: Copied string: Hello
    return 0;
}
Copy after login

strcat

  • Appends a source string to a destination string.
  • Syntax: char *strcat(char *dest, const char *src)
#include <stdio.h>
#include <string.h>

int main() {
    char dest[50] = "Hello";
    char src[] = ", world!";
    strcat(dest, src);
    printf("Concatenated string: %s\n", dest);  // Output: Concatenated string: Hello, world!
    return 0;
}
Copy after login

strncat

  • Appends a specified number of characters from a source string to a destination string.
  • Syntax: char *strncat(char *dest, const char *src, size_t n)
#include <stdio.h>
#include <string.h>

int main() {
    char dest[50] = "Hello";
    char src[] = ", world!";
    strncat(dest, src, 7);
    printf("Concatenated string: %s\n", dest);  // Output: Concatenated string: Hello, world
    return 0;
}
Copy after login

strcmp

  • Compares two strings.
  • Syntax: int strcmp(const char *str1, const char *str2)
#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "Hello";
    char str2[] = "Hello";
    char str3[] = "World";
    printf("Comparison result: %d\n", strcmp(str1, str2));  // Output: Comparison result: 0
    printf("Comparison result: %d\n", strcmp(str1, str3));  // Output: Comparison result: -1 (or another negative value)
    return 0;
}
Copy after login

strncmp

  • Compares a specified number of characters of two strings.
  • Syntax: int strncmp(const char *str1, const char *str2, size_t n)
#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "Hello";
    char str2[] = "Helium";
    printf("Comparison result: %d\n", strncmp(str1, str2, 3));  // Output: Comparison result: 0
    printf("Comparison result: %d\n", strncmp(str1, str2, 5));  // Output: Comparison result: -1 (or another negative value)
    return 0;
}
Copy after login

strchr

  • Searches for the first occurrence of a character in a string.
  • Syntax: char *strchr(const char *str, int c)
#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "Hello, world!";
    char *ptr = strchr(str, 'w');
    if (ptr != NULL) {
        printf("Character found: %s\n", ptr);  // Output: Character found: world!
    } else {
        printf("Character not found\n");
    }
    return 0;
}
Copy after login

strrchr

  • Searches for the last occurrence of a character in a string.
  • Syntax: char *strrchr(const char *str, int c)
#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "Hello, world!";
    char *ptr = strrchr(str, 'o');
    if (ptr != NULL) {
        printf("Last occurrence of character found: %s\n", ptr);  // Output: Last occurrence of character found: orld!
    } else {
        printf("Character not found\n");
    }
    return 0;
}
Copy after login

strstr

  • Searches for the first occurrence of a substring in a string.
  • Syntax: char *strstr(const char *haystack, const char *needle)
#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "Hello, world!";
    char *ptr = strstr(str, "world");
    if (ptr != NULL) {
        printf("Substring found: %s\n", ptr);  // Output: Substring found: world!
    } else {
        printf("Substring not found\n");
    }
    return 0;
}
Copy after login

ctype.h

The ctype.h library in C provides functions for character classification and conversion. These functions help to determine the type of a character (such as whether it is a digit, letter, whitespace, etc.) and to convert characters between different cases.

Here are some of the important functions provided by ctype.h with examples:

isalpha

  • Checks if the given character is an alphabetic letter.
  • Syntax: int isalpha(int c)
#include <stdio.h>
#include <ctype.h>

int main() {
    char ch = 'A';
    if (isalpha(ch)) {
        printf("%c is an alphabetic letter\n", ch);  // Output: A is an alphabetic letter
    } else {
        printf("%c is not an alphabetic letter\n", ch);
    }
    return 0;
}
Copy after login

isdigit

  • Checks if the given character is a digit.
  • Syntax: int isdigit(int c)
#include <stdio.h>
#include <ctype.h>

int main() {
    char ch = '9';
    if (isdigit(ch)) {
        printf("%c is a digit\n", ch);  // Output: 9 is a digit
    } else {
        printf("%c is not a digit\n", ch);
    }
    return 0;
}
Copy after login

isalnum

  • Checks if the given character is an alphanumeric character.
  • Syntax: int isalnum(int c)
#include <stdio.h>
#include <ctype.h>

int main() {
    char ch = 'a';
    if (isalnum(ch)) {
        printf("%c is an alphanumeric character\n", ch);  // Output: a is an alphanumeric character
    } else {
        printf("%c is not an alphanumeric character\n", ch);
    }
    return 0;
}
Copy after login

isspace

  • Checks if the given character is a whitespace character.
  • Syntax: int isspace(int c)
#include <stdio.h>
#include <ctype.h>

int main() {
    char ch = ' ';
    if (isspace(ch)) {
        printf("The character is a whitespace\n");  // Output: The character is a whitespace
    } else {
        printf("The character is not a whitespace\n");
    }
    return 0;
}
Copy after login

isupper

  • Checks if the given character is an uppercase letter.
  • Syntax: int isupper(int c)
#include <stdio.h>
#include <ctype.h>

int main() {
    char ch = 'Z';
    if (isupper(ch)) {
        printf("%c is an uppercase letter\n", ch);  // Output: Z is an uppercase letter
    } else {
        printf("%c is not an uppercase letter\n", ch);
    }
    return 0;
}
Copy after login

islower

  • Checks if the given character is a lowercase letter.
  • Syntax: int islower(int c)
#include <stdio.h>
#include <ctype.h>

int main() {
    char ch = 'z';
    if (islower(ch)) {
        printf("%c is a lowercase letter\n", ch);  // Output: z is a lowercase letter
    } else {
        printf("%c is not a lowercase letter\n", ch);
    }
    return 0;
}
Copy after login

toupper

  • Converts a given character to its uppercase equivalent if it is a lowercase letter.
  • Syntax: int toupper(int c)
#include <stdio.h>
#include <ctype.h>

int main() {
    char ch = 'a';
    char upper = toupper(ch);
    printf("Uppercase of %c is %c\n", ch, upper);  // Output: Uppercase of a is A
    return 0;
}
Copy after login

tolower

  • Converts a given character to its lowercase equivalent if it is an uppercase letter.
  • Syntax: int tolower(int c)
#include <stdio.h>
#include <ctype.h>

int main() {
    char ch = 'A';
    char lower = tolower(ch);
    printf("Lowercase of %c is %c\n", ch, lower);  // Output: Lowercase of A is a
    return 0;
}
Copy after login

math.h

The math.h library in C provides functions for mathematical computations. These functions allow operations like trigonometry, logarithms, exponentiation, and more. Here are some important functions provided by math.h with examples:

Trigonometric Functions

sin

  • Computes the sine of an angle (in radians).
  • Syntax: double sin(double x)
#include <stdio.h>
#include <math.h>

int main() {
    double angle = 0.5;
    double result = sin(angle);
    printf("sin(0.5) = %.4f\n", result);  // Output: sin(0.5) = 0.4794
    return 0;
}
Copy after login

cos

  • Computes the cosine of an angle (in radians).
  • Syntax: double cos(double x)
#include <stdio.h>
#include <math.h>

int main() {
    double angle = 0.5;
    double result = cos(angle);
    printf("cos(0.5) = %.4f\n", result);  // Output: cos(0.5) = 0.8776
    return 0;
}
Copy after login

tan

  • Computes the tangent of an angle (in radians).
  • Syntax: double tan(double x)
#include <stdio.h>
#include <math.h>

int main() {
    double angle = 0.5;
    double result = tan(angle);
    printf("tan(0.5) = %.4f\n", result);  // Output: tan(0.5) = 0.5463
    return 0;
}
Copy after login

Exponential and Logarithmic Functions

exp

  • Computes the base-e exponential function of x, e^x.
  • Syntax: double exp(double x)
#include <stdio.h>
#include <math.h>

int main() {
    double x = 2.0;
    double result = exp(x);
    printf("exp(2.0) = %.4f\n", result);  // Output: exp(2.0) = 7.3891
    return 0;
}
Copy after login

log

  • Computes the natural logarithm (base-e logarithm) of x.
  • Syntax: double log(double x)
#include <stdio.h>
#include <math.h>

int main() {
    double x = 10.0;
    double result = log(x);
    printf("log(10.0) = %.4f\n", result);  // Output: log(10.0) = 2.3026
    return 0;
}
Copy after login

pow

  • Computes x raised to the power of y (x^y).
  • Syntax: double pow(double x, double y)
#include <stdio.h>
#include <math.h>

int main() {
    double base = 2.0;
    double exponent = 3.0;
    double result = pow(base, exponent);
    printf("pow(2.0, 3.0) = %.4f\n", result);  // Output: pow(2.0, 3.0) = 8.0000
    return 0;
}
Copy after login

sqrt

  • Computes the square root of x.
  • Syntax: double sqrt(double x)
#include <stdio.h>
#include <math.h>

int main() {
    double x = 25.0;
    double result = sqrt(x);
    printf("sqrt(25.0) = %.4f\n", result);  // Output: sqrt(25.0) = 5.0000
    return 0;
}
Copy after login

Rounding and Remainder Functions

ceil

  • Computes the smallest integer value greater than or equal to x.
  • Syntax: double ceil(double x)
#include <stdio.h>
#include <math.h>

int main() {
    double x = 3.14;
    double result = ceil(x);
    printf("ceil(3.14) = %.4f\n", result);  // Output: ceil(3.14) = 4.0000
    return 0;
}
Copy after login

floor

  • Computes the largest integer value less than or equal to x.
  • Syntax: double floor(double x)
#include <stdio.h>
#include <math.h>

int main() {
    double x = 3.14;
    double result = floor(x);
    printf("floor(3.14) = %.4f\n", result);  // Output: floor(3.14) = 3.0000
    return 0;
}
Copy after login

round

  • Rounds x to the nearest integer value.
  • Syntax: double round(double x)
#include <stdio.h>
#include <math.h>

int main() {
    double x = 3.75;
    double result = round(x);
    printf("round(3.75) = %.4f\n", result);  // Output: round(3.75) = 4.0000
    return 0;
}
Copy after login

The above is the detailed content of C, Essential Libraries. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1240
24
C# vs. C  : History, Evolution, and Future Prospects C# vs. C : History, Evolution, and Future Prospects Apr 19, 2025 am 12:07 AM

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

The Future of C   and XML: Emerging Trends and Technologies The Future of C and XML: Emerging Trends and Technologies Apr 10, 2025 am 09:28 AM

The future development trends of C and XML are: 1) C will introduce new features such as modules, concepts and coroutines through the C 20 and C 23 standards to improve programming efficiency and security; 2) XML will continue to occupy an important position in data exchange and configuration files, but will face the challenges of JSON and YAML, and will develop in a more concise and easy-to-parse direction, such as the improvements of XMLSchema1.1 and XPath3.1.

The Continued Use of C  : Reasons for Its Endurance The Continued Use of C : Reasons for Its Endurance Apr 11, 2025 am 12:02 AM

C Reasons for continuous use include its high performance, wide application and evolving characteristics. 1) High-efficiency performance: C performs excellently in system programming and high-performance computing by directly manipulating memory and hardware. 2) Widely used: shine in the fields of game development, embedded systems, etc. 3) Continuous evolution: Since its release in 1983, C has continued to add new features to maintain its competitiveness.

C# vs. C  : Learning Curves and Developer Experience C# vs. C : Learning Curves and Developer Experience Apr 18, 2025 am 12:13 AM

There are significant differences in the learning curves of C# and C and developer experience. 1) The learning curve of C# is relatively flat and is suitable for rapid development and enterprise-level applications. 2) The learning curve of C is steep and is suitable for high-performance and low-level control scenarios.

C   and XML: Exploring the Relationship and Support C and XML: Exploring the Relationship and Support Apr 21, 2025 am 12:02 AM

C interacts with XML through third-party libraries (such as TinyXML, Pugixml, Xerces-C). 1) Use the library to parse XML files and convert them into C-processable data structures. 2) When generating XML, convert the C data structure to XML format. 3) In practical applications, XML is often used for configuration files and data exchange to improve development efficiency.

Modern C   Design Patterns: Building Scalable and Maintainable Software Modern C Design Patterns: Building Scalable and Maintainable Software Apr 09, 2025 am 12:06 AM

The modern C design model uses new features of C 11 and beyond to help build more flexible and efficient software. 1) Use lambda expressions and std::function to simplify observer pattern. 2) Optimize performance through mobile semantics and perfect forwarding. 3) Intelligent pointers ensure type safety and resource management.

The C   Community: Resources, Support, and Development The C Community: Resources, Support, and Development Apr 13, 2025 am 12:01 AM

C Learners and developers can get resources and support from StackOverflow, Reddit's r/cpp community, Coursera and edX courses, open source projects on GitHub, professional consulting services, and CppCon. 1. StackOverflow provides answers to technical questions; 2. Reddit's r/cpp community shares the latest news; 3. Coursera and edX provide formal C courses; 4. Open source projects on GitHub such as LLVM and Boost improve skills; 5. Professional consulting services such as JetBrains and Perforce provide technical support; 6. CppCon and other conferences help careers

Beyond the Hype: Assessing the Relevance of C   Today Beyond the Hype: Assessing the Relevance of C Today Apr 14, 2025 am 12:01 AM

C still has important relevance in modern programming. 1) High performance and direct hardware operation capabilities make it the first choice in the fields of game development, embedded systems and high-performance computing. 2) Rich programming paradigms and modern features such as smart pointers and template programming enhance its flexibility and efficiency. Although the learning curve is steep, its powerful capabilities make it still important in today's programming ecosystem.

See all articles