快速学C语言——第19章:C语言常用开发库
第19章C语言常用开发库C语言的标准库提供了丰富的函数来帮助开发者完成各种常见任务。掌握这些标准库的使用可以大大提高编程效率。⚠️本章只给出日常开发中常用的函数19.1 标准输入输出库stdio.hstdio.h是最常用的库提供输入输出功能。19.1.1 基本输入输出函数#includestdio.hintmain(){intage;charname[20];// 输出函数printf(请输入你的姓名: );scanf(%s,name);printf(请输入你的年龄: );scanf(%d,age);printf(你好 %s, 你今年 %d 岁\n,name,age);return0;}19.1.2 文件操作#includestdio.hintmain(){FILE*file;// 写入文件filefopen(test.txt,w);if(file!NULL){fprintf(file,这是一行文本\n);fclose(file);}// 读取文件filefopen(test.txt,r);if(file!NULL){charbuffer[100];fgets(buffer,sizeof(buffer),file);printf(文件内容: %s,buffer);fclose(file);}return0;}19.2 字符串处理库string.hstring.h提供字符串操作函数。#includestdio.h#includestring.hintmain(){charstr1[20]Hello;charstr2[20]World;charresult[40];// 字符串长度printf(str1长度: %zu\n,strlen(str1));// 字符串复制strcpy(result,str1);printf(复制后: %s\n,result);// 字符串连接strcat(result, );strcat(result,str2);printf(连接后: %s\n,result);// 字符串比较if(strcmp(str1,str2)0){printf(字符串相等\n);}else{printf(字符串不相等\n);}return0;}19.3 字符处理库ctype.hctype.h提供字符分类和转换函数。#includestdio.h#includectype.hintmain(){charchA;// 字符类型判断printf(%c 是字母: %d\n,ch,isalpha(ch));printf(%c 是大写: %d\n,ch,isupper(ch));printf(%c 是数字: %d\n,ch,isdigit(ch));// 字符转换charlowertolower(ch);charuppertoupper(b);printf(大写转小写: %c\n,lower);printf(小写转大写: %c\n,upper);return0;}19.4 数学库math.hmath.h提供数学计算函数。#includestdio.h#includemath.hintmain(){doublex4.0;doubley2.5;// 基本数学运算printf(平方根: %.2f\n,sqrt(x));printf(幂运算: %.2f\n,pow(x,y));printf(绝对值: %.2f\n,fabs(-3.14));printf(向上取整: %.2f\n,ceil(y));printf(向下取整: %.2f\n,floor(y));return0;}19.5 标准库stdlib.hstdlib.h提供通用工具函数。19.5.1 内存分配#includestdio.h#includestdlib.hintmain(){// 动态内存分配int*arr(int*)malloc(5*sizeof(int));if(arr!NULL){for(inti0;i5;i){arr[i]i*10;}for(inti0;i5;i){printf(%d ,arr[i]);}printf(\n);free(arr);}return0;}19.5.2 类型转换#includestdio.h#includestdlib.hintmain(){// 字符串转数字charstr[]12345;intnumatoi(str);printf(字符串转整数: %d\n,num);charfloat_str[]3.14;doublepiatof(float_str);printf(字符串转浮点数: %.2f\n,pi);return0;}19.5.3 随机数#includestdio.h#includestdlib.h#includetime.hintmain(){// 设置随机数种子srand(time(NULL));// 生成随机数for(inti0;i5;i){printf(随机数: %d\n,rand()%100);// 0-99的随机数}return0;}19.6 时间库time.htime.h提供时间处理函数。#includestdio.h#includetime.hintmain(){// 获取当前时间time_tcurrent_time;time(current_time);printf(当前时间戳: %ld\n,current_time);// 转换为可读格式char*time_strctime(current_time);printf(当前时间: %s,time_str);return0;}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2609781.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!