C库提供了三个读取字符串的函数:gets( ) fgets( ) scanf( )。

C库提供了三个读取字符串的函数:gets( )  fgets( )  scanf( )。

gets()---get string 从系统的标准输入设备(通常是键盘)获得一个字符串。因为字符串没有预定的长度,所以gets()需要知道输入何时结束。解决办法是在读字符串直到遇到一个换行符(/n),按回车键可以产生这个字符。它读取换行符之前(不包括换行符)的所有字符,在这些字符后加一个空字符(/0)。它会丢弃换行符。

定义函数   char *gets(char *s)

返回值     gets()若成功则返回s指针,返回NULL则表示有错误发生。

[c-sharp] view plain copy print ?
  1. /* name1.c -- reads a name */ 
  2. #include <stdio.h>  
  3. #define MAX 81   
  4. int main(void)  
  5. {  
  6.     char name[MAX];  /* 分配空间                  */  
  7.   
  8.     printf("Hi, what's your name?/n");  
  9.     gets(name);      /* 把字符串放进name数组中 */  
  10.     printf("Nice name, %s./n", name);  
  11.    
  12.     return 0;  
  13. }  

 

fgets()---是为文件I/O设计的

定义函数  fgets(char *s,int size,FILE *stream)

返回值    若成功则返回s指针,返回NULL则表示有错误发生。

fgets()用来从参数stream所指的文件内读入字符并存到参数s所指的内存空间,知道出现换行符、读到文件尾或者是读了size-1个字符为止。fgets()会把换行符存储到字符串里。

[c-sharp] view plain copy print ?
  1. /* name3.c -- reads a name using fgets() */ 
  2. #include <stdio.h>  
  3. #define MAX 81   
  4. int main(void)  
  5. {  
  6.     char name[MAX];  
  7.     char * ptr;  
  8.   
  9.     printf("Hi, what's your name?/n");  
  10.     ptr = fgets(name, MAX, stdin);  
  11.     printf("%s? Ah! %s!/n", name, ptr);  
  12.       
  13.     return 0;  
  14. }  

运行结果

Hi, what's your name?

Jon Dough

Jon Dough

? AH! Jon Dough

!

 

scanf( )---格式化字符串输入

定义函数  int scanf(const char *format,。。。。。)

返回值   成功则返回参数数目,失败则返回-1

参数   size---允许输入的数据长度

         l      ---以long int或double型保存

         h    ---short int型保存

         s    ---字符串

         c    ---字符

[c-sharp] view plain copy print ?
  1. /* scan_str.c -- using scanf() */ 
  2. #include <stdio.h>   
  3. int main(void)  
  4. {  
  5.     char name1[11], name2[11];  
  6.     int count;  
  7.   
  8.     printf("Please enter 2 names./n");  
  9.     count = scanf("%5s %10s",name1, name2);  
  10.     printf("I read the %d names %s and %s./n",  
  11.            count, name1, name2);  
  12.       
  13.     return 0;  
  14. }  

运行结果

Please enter 2 names.
Jesse Jukes
I read the 2 names Jesse and Jukes.


Please enter 2 names.
Liza Applebottam
I read the 2 names Liza and Applebotta.

Please enter 2 names.
Portensia Callowit
I read the 2 names Porte and nsia.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值