#include<stdio.h>
#define MSG "oooooooooooooo!"
int main()
{
char word[100]="i like apple.";
char * pt1="me too.";
puts("some sentence:");
puts(word);
puts(pt1);
puts(MSG);
word[8]='d';
puts(word);
return 0;
}
some sentence:
i like apple.
me too.
oooooooooooooo!
i like adple.
请按任意键继续. . .
总结
:字符串可以由数组,指针,全局定义,
puts()函数输出字符串,且在末尾默认\n
#include<stdio.h>
int main()
{
char word[50]="hello,and""how are""you""today!";
puts(word);
char a[50]="\"i am stupid\"";
puts(a);
}
hello,andhow areyoutoday!
“i am stupid”
请按任意键继续. . .
总结
:如果字符串之间没有间隔,或用空白符隔开,c默认串联起来
要在字符串里面使用双引号,要在前面加\
问题:
字符串数组与字符串指针的异同是什么?
如果不改变字符串,使用指针方便
字符串输入:
gets();fgets ( ) ; gets-s();
1.gets()用法
#include<stdio.h>
int main()
{
char word[80];
puts("ENTER A STRING,PLEASE:");
gets(word);
puts(word);
}
ENTER A STRING,PLEASE:
O MY GOD!
O MY GOD!
请按任意键继续. . .
总结:
gets()常用puts()连用
gets()无法判断数组是否装得下输入行。溢出字符可能会擦写程序中其他数据,具有不安全性,不推荐使用。
fgets()用法
#include<stdio.h>
int main()
{
char word[6];
puts("PLEASE ENTER A STRING:");
fgets(word,6,stdin); //fgts(数组名,最大输入数量,stdin)
puts(word);
fputs(word,stdout);
puts("ok!");
}
(1)
PLEASE ENTER A STRING:
mos
mos
mos
ok!
请按任意键继续. . .
(2)
PLEASE ENTER A STRING:
aaabbbcccddd
aaabb
aaabbok!
请按任意键继续. . .
如果输入超过限制长度,fgets只读取6个字符,并以 aaabb\0 的形式储存在数组中
#include<stdio.h>
int main()
{
char word[10];
puts("PLEASE ENTER A STRING:");
while(fgets(word,10,stdin)!=NULL && word[0]!='\n')
fputs(word,stdout); //溢出字符在缓存区
puts("end!!");
}
PLEASE ENTER A STRING:
ooooooooo my god!!!
ooooooooo my god!!!
end!!
请按任意键继续. . .
总结:
fgts()常与fputs()连用
gets()不保留换行符,fgets()会保留
fputs()不会在末尾自动添加换行符 [与puts()不一样]
推荐使用
#include<stdio.h>
int main()
{
char word[10];
while(fgets(word,10,stdin)!=NULL &&word[0]!='\n')
fputs(word,stdout);
puts("over!");
return 0;
}
111111111111111111111111111111111
111111111111111111111111111111111
over!
请按任意键继续. . .
#include<stdio.h>
int main()
{
char word[10];
int i;
while(fgets (word,10,stdin) !=NULL && word[0]!='\n')
{
i=0;
while(word[i]!='\n'&&word[i]!='\0')
i++;
if(word[i]=='\n')
word[i]='\0';
else
while(getchar()!='\n')
continue;
puts(word);
}
return 0;
}
gets-s()用法
scanf()函数
#include<stdio.h>
int main()
{
char name1[10], name2[10];
int count;
printf("please enter two names.\n");
count=scanf("%5s %10s",name1,name2);
printf("i read the %d name %s and %s",count,name1,name2);
}
please enter two names.
petter oversinmg
i read the 2 name pette and r请按任意键继续. . .
总结
%s读取字符
scanf()更像是获取单词函数
如果指定字段宽度,如%5是,那么scanf()将读取5个字符或读到第一个空白符停止
字符串输出
puts();fputs();printf();
puts()末尾自动加换行符,fputs()和prints()不会;
printf(“%s\n”,string)=puts(string);
字符串函数
使用需要添加头文件#include<string.h>
strlen()-----------------------统计字符串的长度
strcat()----------------------拼接字符串
strncat()
strcmp()------------------把用户响应与已存储字符作比较
strlen( )
{
char word[20]="ooo my god";
printf("%d\n",strlen(word));
return 0;
}
10
请按任意键继续. . .
(空字符也算一个字符)
strcat()
????????有bug
char word[10]="flower is";
char len[10]=" good";
puts(strcat(word,len));
return 0;
flower is good
请按任意键继续. . .