1、gets()函数:
a、读取整行输入输入,直至遇到换行符,然后丢弃换行符,在字符的结尾添加一个空字符使其成为一个C字符串(经常和puts()函数搭配使用-->显示字符串,并且在末尾添加换行符),对应a输入
b、隐患:如果输入的字符过长,会导致缓冲区溢出,即多余的字符超出了指定的目标空间(对应b输入)
/*getsputs.c--使用gets()和puts()*/
#include <stdio.h>
#define STLEN 81
int main(void)
{
char words[STLEN];
puts("Enter a string,please.");
gets(words); //典型用法
printf("Your string twice:\n");
printf("%s\n",words); //效果相同
puts(words); //同上
puts("Done.");
return 0;
}
/*****************************************
a输入
Enter a string,please.
I want to learn about string theory!
Your string twice:
I want to learn about string theory!
I want to learn about string theory!
Done.
*****************************************/
/****************************************
b输入
Enter a string,please.
warning:this program uses gets(),which is unsafe.
I think I'll be just fine.
Your string twice:
I think I'll be just fine.
I think I'll be just fine.
Done.
Segmentation fault:11
****************************************/
2、fgets()函数:
a、第二个参数限制读入字符的最大数量,如果参数的值是n,那么fgets()将读入n-1个字符,或者读到遇到的第一个换行符为止
b、读取到一个换行符,会将其储存在字符串中
c、fgets()的第三个参数指明要读入的文件,如果从键盘输入数据,则以stdin(标准输入)作为参数,该标识符定义在stdio.h中(fgets()函数通常和fputs()函数使用,该函数不在字符串末尾添加换行符,如果要显示在屏幕上,则使用stdout作为参数)
/*fgetsl.c--使用fgets()和fputs()*/
#include <stdio.h>
#define STLEN 14
int main(void)
{
char words[STLEN];
puts("Enter a string.please.");
fgets(words,STLEN,stdin);
printf("Your string twice(puts(),then fputs())\n");
puts(words);
fputs(words,stdout);
puts("Enter another string,please.");
fgets(words,STLEN,stdin);
printf("Your string twice (puts(),then fputs()):\n");
puts(words);
fputs(words,stdout);
puts("Done");
return 0;
}
**************************************************
Enter a string.please.
apple tie
Your string twice(puts(),then fputs())
apple tie
apple tie
Enter another string,please.
strawberry shortcake
Your string twice (puts(),then fputs()):
strawberry sh
strawberry shDone
***************************************************
3、gets_s()函数:
a、只从标准输入中读取数据,无需第三个参数
b、如果读取到换行符,丢弃他而不是储存他
c、如果读取到最大字符数都未读取到换行符,会执行以下几步:目标数组首字符设置为空字符,读取并且丢弃随后的输入直至读到换行符或者文件结尾,然后返回空指针,接着调用依赖实现的"处理函数"
4、scanf()函数:
从第一个非空白字符作为字符串的开始,如果使用%s转换说明,以下一个空白字符(空行,空格,制表符或者换行符)作为字符串的结束(字符串不包括空白字符),如果指定了字符宽度,如%10s,那么scanf()函数将读取10个字符或读到第1个空白字符停止(先满足的条件即是结束输入的条件)
输入语句 原输入序列 name中的内容 剩余输入序列
scanf("%s",name); Fleebert Hup Fleebert _Hup
scanf("%5s",name); Fleebert Hup Fleeb ert Hu
scanf("%5s",name); Ann Ular Ann _Ular
/*scan_str.c--使用scanf()*/
#include <stdio.h>
int main(void)
{
char name1[11],name2[11];
int count;
printf("Please enter 2 names.\n");
count = scanf("%5s %10s",name1,name2);
printf("I need the %d name %s and %s.\n",count,name1,name2);
return 0;
}
/***************************************************
Please enter 2 names.
Jesse Jukes
I need the 2 name Jesse and Jukes.
Please enter 2 names.
Liza Applebottham
I need the 2 name Liza and Applebotth.
Please enter 2 names.
Portensia Callowit
I need the 2 name Porte and nsia.
***************************************************/