文档详情

C第6章数组.ppt

发布:2017-02-01约1.6万字共45页下载文档
文本预览下载声明
* * * * * * * * * * * * * * * * * * * * * * * * * * * * 例 用%c #include stdio.h main() { char str[5]; int i; for(i=0;i5;i++) scanf(“%c”,str[i]); for(i=0;i5;i++) printf(“%c”,str[i]); } 例 用%s #include stdio.h main() { char str[5]; scanf(“%s”,str); printf(“%s”,str); } 用字符数组名,不要加 输入串长度数组维数 遇空格或回车结束 自动加\0 用字符数组名, 遇\0结束 逐个字符I/O: %c 整个字符串I/O:%s 6.3.4 字符串的输入输出 例 #include stdio.h main( ) { char a[5]={H,e,l,l,o}; printf(“%s”,a); } 例 #include stdio.h main( ) { char a[]=“Hello”; printf(“%s”,a); } 结果:Hello(随机) H  e  l  l  o 0 2 3 1 4 结果:Hello 用“%s”输出时,遇\0结束 #include stdio.h main() { char a[]={h,e,l,\0,l,o,\0}; printf(%s,a); } 例 输出:hel \0 o l \0 l e h 数组中有多个\0时, 遇第一个结束 #include stdio.h main() { int i; char a[5]; scanf(%s,a); for(i=0;i=4;i++) printf(%d,,a[i]); } 运行情况: (1)若输入hel, 正常 (2)若输入hell,正常 (3)若输入hello,也可以,但不提倡 \0 l e h \0 l l e h O l l e h 输入字符串长度数组维数 H o w \0 a r e \0 y o u ? \0 #include stdio.h main() { char a[15],b[5],c[5]; scanf(%s%s%s,a,b,c); printf(a=%s\nb=%s\nc=%s\n,a,b,c); scanf(%s,a); printf(a=%s\n,a); } 运行情况: 输入:How are you? 输出:a=How b=are c=you? 输入:How are you? 输出:a=How 运行情况: 输入:How are you? scanf中%s输入时,遇 空格或回车结束 例 字符串输入举例 字符串输出函数puts 格式:puts(字符数组) 功能:向显示器输出字符串(输出完,换行) 说明:字符数组必须以\0结束 字符串输入函数gets 格式:gets(字符数组) 功能:从键盘输入一以回车结束的字符串放入 字符数组中,并自动加\0 说明:输入串长度应小于字符数组维数 例 #include stdio.h #include string.h main( ) { char string[80]; printf(“Input a string:”); gets(string); puts(string); } 输入: How are you? 输出: How are you? 包含在头文件 string.h,大量字符串函数参考教材372页。 6.3.6 字符串处理函数 字符串连接函数strcat 格式:strcat(char *strDestination, const char *strSource ) 功能:把strSource连到strDestination后面 返值:返回strDestination的首地址 说明:?strDestination必须足够大 ?连接前,两串均以\0结束; 连接后,串1的 \0取消,新串最后加\0 字符串拷贝函数strcpy 格式:strcpy(char *strDestination, const char *strSource ) 功能:将strSource ,拷贝到strDestination中去 返值:返回strDestination的首地址 说明:?strDestination必须足够大 ?拷贝时\0一同拷贝 ?不能使用赋值语句为一个字符数组赋值 例 char str1[20],str2[20]; str1=
显示全部
相似文档