02-字符串的输入与输出(PPT)
合集下载
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
(2)用puts()来进行字符串的输出。
调用格式:
puts(字符数组名、字符指针名或字符串常量)
#include <stdio.h> int main() {
char ch[15]="Hello"; char *sp="world!"; puts(ch); puts(sp); puts("Hello world!"); return 0; }
“%s”表示按字符串格式进行输 入或输出
#include <stdio.h> int main() {
char ch[15]; scanf("%s",ch); printf("%s\n",ch); return 0; }
不能写成scanf("%s",&ch)
注意:C语言规定,用scanf()输入字符串是以空格、回车或制表符作为 字符串的分隔符。当遇到这些符号时,就认为字符串输入结束。
char ch[15],s; scanf("%s",ch); s=getchar(); printf("%s",ch); return 0; }
printf("%s%c",ch,s);
(2)用gets()来进行字符串的输入
用gets()可以直接输入字符串,直至遇到回车键为止,一般格式为:
gets(字符数组名)
用puts() 输出字符串,遇到“\0”结束字符串输出,同时自动换行。
利用格式输入输出函数scanf()与printf(),结合格式控制符“%s”,能够很方便地 实现字符串的输入与输出。
gets()与puts() 是专门对字符串进行输入输出的一对函数,不需要进行格式控制, 使用起来更加方便和简洁。
专题10 字符串处理 1. 使用字符数组表示字符串 2. 使用字符指针表示字符串 3. 字符串的输入与输出 4. 常用的字符串处理函数 5. 字符串应用举例
10.3 字符串的输入与输出 字符串的输入函数 字符串的输出函数
1 字符串的输入函数
(1)用scanf()函数来实现字符串的输入
#include <stdio.h> int main() {
#include <stdio.h> int main() {
char ch[15]; gets(ch); printf("%s\n",(1)用printf()来进行字符串的输出。
#include <stdio.h> int main() {
char ch[15]="Hello"; char *sp="world!"; printf("%s %s\n",ch,sp); return 0; }
如何才能输入空格符? 可以指定字符串输入的结束符。
#include <stdio.h> int main() {
char ch[15]; scanf("%[^\n]",ch); printf("%s\n",ch); return 0; }
指定“\n”,即换行符,作为字符串 输入的结束符。
#include <stdio.h> int main() {
int i; char ch[15];
for(i=0;i<12;i++) scanf("%c",&ch[i]);
ch[12]='\0'; for(i=0;ch[i]!='\0';i++)
printf("%c",ch[i]); printf("\n"); return 0; }
scanf("%s",ch); printf("%s",ch);