C庫提供了三個讀取字符串的函數:gets( ) fgets( ) scanf( )。

C庫提供了三個讀取字符串的函數:gets( )  fgets( )  scanf( )。

gets()---get string 從系統的標準輸入設備(通常是鍵盤)獲得一個字符串。因爲字符串沒有預定的長度,所以gets()需要知道輸入何時結束。解決辦法是在讀字符串直到遇到一個換行符(/n),按回車鍵可以產生這個字符。它讀取換行符之前(不包括換行符)的所有字符,在這些字符後加一個空字符(/0)。它會丟棄換行符。

定義函數   char *gets(char *s)

返回值     gets()若成功則返回s指針,返回NULL則表示有錯誤發生。

  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()會把換行符存儲到字符串裏。

  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    ---字符

  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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章