gets ()- 讀取一行

格式

#include <stdio.h>
char *gets(char *buffer);

語言層次

ANSI

安全執行緒

說明

gets() 函數會從標準輸入串流 stdin 讀取一行,並將它儲存在 緩衝區中。 此行由所有字元組成,直到 (但不包括) 第一個換行字元 (\n) 或 EOF。 然後, gets() 函數會在傳回行之前,將換行字元 (如果已讀取) 取代為空值字元 (\0)。

回覆值

如果成功, gets() 函數會傳回其引數。 NULL 指標回覆值指出發生錯誤,或檔案結尾狀況沒有讀取任何字元。 請使用 ferror() 函數或 feof() 函數來判斷發生了哪些狀況。 如果發生錯誤,則儲存在 buffer 中的值未定義。 如果發生檔案結尾狀況,則不會變更 buffer

範例

此範例從 stdin取得一行輸入。
#include  <stdio.h>
 
#define MAX_LINE 100
 
int main(void)
{
   char line[MAX_LINE];
   char *result;
 
   printf("Please enter a string:\n");
   if ((result = gets(line)) != NULL)
      printf("The string is: %s\n", line);
   else if (ferror(stdin))
      perror("Error");
}

相關資訊