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- /* name1.c -- reads a name */
- #include <stdio.h>
- #define MAX 81
- int main(void)
- {
- char name[MAX]; /* 分配空間 */
- printf("Hi, what's your name?/n");
- gets(name); /* 把字串放進name陣列中 */
- printf("Nice name, %s./n", name);
- return 0;
- }
fgets()---是為檔案I/O設計的
定義函式 fgets(char *s,int size,FILE *stream)
返回值 若成功則返回s指標,返回NULL則表示有錯誤發生。
fgets()用來從引數stream所指的檔案內讀入字元並存到引數s所指的記憶體空間,知道出現換行符、讀到檔案尾或者是讀了size-1個字元為止。fgets()會把換行符儲存到字串裡。
[c-sharp] view plaincopyprint?- /* name3.c -- reads a name using fgets() */
- #include <stdio.h>
- #define MAX 81
- int main(void)
- {
- char name[MAX];
- char * ptr;
- printf("Hi, what's your name?/n");
- ptr = fgets(name, MAX, stdin);
- printf("%s? Ah! %s!/n", name, ptr);
- return 0;
- }
執行結果
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?- /* scan_str.c -- using 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 read the %d names %s and %s./n",
- count, name1, name2);
- return 0;
- }
執行結果
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.