_cgets, _cgetws

從主控台取得字元字串。 這些函式有更安全的版本可供使用;請參閱 _cgets_s_cgetws_s

重要

這些函式已被取代。 自 Visual Studio 2015 起,這些函式即無法在 CRT 中使用。 這些函式 (_cgets_s 及 _cgetws_s) 的安全版本仍可使用。 如需這些替代函式的詳細資訊,請參閱 _cgets_s_cgetws_s

重要

這個 API 不能用於在 Windows 執行階段中執行的應用程式。 如需詳細資訊,請參閱 CRT functions not supported in Universal Windows Platform apps (通用 Windows 平台應用程式中不支援的 CRT 函式)。

語法

char *_cgets(
   char *buffer
);
wchar_t *_cgetws(
   wchar_t *buffer
);
template <size_t size>
char *_cgets(
   char (&buffer)[size]
); // C++ only
template <size_t size>
wchar_t *_cgetws(
   wchar_t (&buffer)[size]
); // C++ only

參數

buffer
資料的儲存位置。

傳回值

_cgets_cgetws 會在 buffer[2]傳回字串開頭的指標。 如果 bufferNULL ,這些函式會叫用不正確參數處理常式,如參數驗證 中所述 。 如果允許繼續執行,這些函式會傳回 NULL,並將 errno 設為 EINVAL

備註

這些函式會從主控台讀取字元字串,並將字串及其長度儲存在 buffer指向的位置。 buffer 參數必須是指向字元陣列的指標。 陣列的第一個項目 buffer[0]必須包含要讀取之字串的長度上限 (字元)。 陣列必須包含足夠的元素來保存字串、終止的 Null 字元 ('\0') 和 2 個額外的位元組。 此函式會讀取歸位/換行字元 (CR-LF) 組合之前的所有字元,或讀取指定數量的字元。 字串會從 buffer[2]開始儲存。 若函式讀取了 CR LF,將會儲存 null 字元 ('\0')。 此函式會將該字串的實際長度儲存在第二個陣列項目 buffer[1]中。

因為在主控台視窗中呼叫 _cgets_cgetws 時,所有編輯索引鍵都會在使用中,所以按 F3 鍵會重複上一個輸入的項目。

在 C++ 中,這些函式具有樣板多載,可以叫用這些函式的更新且安全的對應版本。 如需詳細資訊,請參閱 保護範本多載

根據預設,此函式的全域狀態會限定于應用程式。 若要變更此行為,請參閱 CRT 中的全域狀態。

泛型文字常式對應

Tchar.h 常式 _UNICODE_MBCS 未定義 _MBCS 定義 _UNICODE 定義
_cgetts _cgets _cgets _cgetws

需求

常式 必要的標頭
_cgets <conio.h>
_cgetws <conio.h > 或 < wchar.h>

如需相容性詳細資訊,請參閱相容性

範例

// crt_cgets.c
// compile with: /c /W3
// This program creates a buffer and initializes
// the first byte to the size of the buffer. Next, the
// program accepts an input string using _cgets and displays
// the size and text of that string.

#include <conio.h>
#include <stdio.h>
#include <errno.h>

int main( void )
{
   char buffer[83] = { 80 };  // Maximum characters in 1st byte
   char *result;

   printf( "Input line of text, followed by carriage return:\n");

   // Input a line of text:
   result = _cgets( buffer ); // C4996
   // Note: _cgets is deprecated; consider using _cgets_s
   if (!result)
   {
      printf( "An error occurred reading from the console:"
              " error code %d\n", errno);
   }
   else
   {
      printf( "\nLine length = %d\nText = %s\n",
              buffer[1], result );
   }
}

      A line of input.Input line of text, followed by carriage return:
Line Length = 16
Text = A line of input.

另請參閱

主控台和埠 I/O
_getch, _getwch