1. 程式人生 > >C庫提供了三個讀取字串的函式:gets( ) fgets( ) scanf( )。

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

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

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

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

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

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

fgets()---是為檔案I/O設計的

定義函式  fgets(char *s,int size,FILE *stream)

返回值    若成功則返回s指標,返回NULL則表示有錯誤發生。

fgets()用來從引數stream所指的檔案內讀入字元並存到引數s所指的記憶體空間,知道出現換行符、讀到檔案尾或者是讀了size-1個字元為止。fgets()會把換行符儲存到字串裡。

[c-sharp] view plaincopyprint?
  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.     printf("Hi, what's your name?/n");  
  9.     ptr = fgets(name, MAX, stdin);  
  10.     printf("%s? Ah! %s!/n", name, ptr);  
  11. return 0;  
  12. }  

執行結果

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 plaincopyprint?
  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.     printf("Please enter 2 names./n");  
  8.     count = scanf("%5s %10s",name1, name2);  
  9.     printf("I read the %d names %s and %s./n",  
  10.            count, name1, name2);  
  11. return 0;  
  12. }  

執行結果

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.