上一章我们大致梳理了标准库的整体框架,这一节选取高频头文件动手实操,涵盖字符串处理、数学运算、通用工具、字符判断与时间相关功能。熟悉之后就可以直接在代码中调用。

string.h:字符串处理

字符串函数在 string.h 里,完整讲解见"C 语言字符串函数库",这里快速过一遍最常用的:

#include <stdio.h>
#include <string.h>

int main() {
    char s1[20] = "Hello ";
    char s2[] = "World";

    printf("长度: %lu\n", strlen("Hello"));   // 5
    strcat(s1, s2);                            // s1 -> "Hello World"
    printf("%s\n", s1);
    printf("比较: %d\n", strcmp("a", "b"));    // 负数:a 小于 b
    return 0;
}

stdlib.h:通用工具

动态内存(malloc/free)、字符串转数字(atoi/atof)、排序(qsort)、随机数(rand)、退出(exit)全在这:

#include <stdio.h>
#include <stdlib.h>

int main() {
    // 字符串转整数
    int n = atoi("42");
    printf("atoi: %d\n", n);

    // 随机数(0~99)
    printf("rand: %d\n", rand() % 100);

    // 动态分配并释放
    int *arr = (int *)malloc(5 * sizeof(int));
    arr[0] = 10;
    printf("malloc: %d\n", arr[0]);
    free(arr);
    return 0;
}

math.h:数学函数

开方、幂、取绝对值、四舍五入都在这,编译时部分系统要加 -lm:

#include <stdio.h>
#include <math.h>

int main() {
    printf("sqrt(16) = %.1f\n", sqrt(16.0));     // 4.0
    printf("pow(2,10) = %.0f\n", pow(2.0, 10.0)); // 1024
    printf("fabs(-3.5) = %.1f\n", fabs(-3.5));    // 3.5
    printf("ceil(2.1) = %.1f\n", ceil(2.1));      // 3.0
    printf("floor(2.9) = %.1f\n", floor(2.9));    // 2.0
    return 0;
}

ctype.h:字符分类与转换

判断一个字符是不是数字、字母,或者做大小写转换:

#include <stdio.h>
#include <ctype.h>

int main() {
    char c1 = '5', c2 = 'a', c3 = 'Z';

    printf("isdigit('%c') = %d\n", c1, isdigit(c1));  // 非0
    printf("isalpha('%c') = %d\n", c2, isalpha(c2));  // 非0
    printf("toupper('%c') = %c\n", c2, toupper(c2));  // A
    printf("tolower('%c') = %c\n", c3, tolower(c3));  // z
    return 0;
}

time.h:日期时间

time() 取当前时间戳,difftime() 算时间差,ctime() 转成可读字符串:

#include <stdio.h>
#include <time.h>

int main() {
    time_t start, end;

    start = time(NULL);
    printf("当前时间戳: %ld\n", (long)start);

    // 模拟一段工作
    for (volatile int i = 0; i < 100000000; i++);

    end = time(NULL);
    printf("程序耗时: %.2f 秒\n", difftime(end, start));
    return 0;
}

assert.h:程序断言

assert() 在条件为假时终止程序并打印出错位置,用于调试期检查不该发生的事:

#include <stdio.h>
#include <assert.h>

int main() {
    int x = 10;
    assert(x > 0);    // 为真,继续
    printf("x = %d\n", x);

    assert(x < 5);    // 为假,程序在此中止并报错
    return 0;
}

怎么选函数

  • 打印/输入 → stdio.h
  • 字符串 → string.h
  • 内存/转换/随机/排序 → stdlib.h
  • 数学 → math.h
  • 字符 → ctype.h
  • 时间 → time.h
  • 调试断言 → assert.h

建立需求与头文件的对应思路,使用时查阅函数原型,标准库就能作为稳定可靠的工具库。