_cgets、_cgetws

从控制台获取一个字符串。 有关这些函数的更多安全版本,请参见 _cgets_s、_cgetws_s

重要

此 API 不能用于在 Windows 运行时中执行的应用程序。有关详细信息,请参见 CRT functions not supported with /ZW(CRT 函数不支持使用/ZW)。

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
    数据的存储位置。

返回值

在 buffer[2]中,_cgets 和 _cgetws 返回指向该字符串开头的指针。 如果 buffer 为 NULL,则函数调用无效参数处理程序, 如 参数验证所述。 如果允许执行继续,则这些函数返回 NULL 并将 errno 设置为 EINVAL。

备注

这些函数从控制台读取字符串,并在 buffer指向的位置存储该字符串及其长度。 buffer 参数必须是指向字符数组的指针。 buffer[0]的第一个数组元素,必须包含最大长度 (在字符串中) 的用于读取的字符串。 数组必须有足够的元素包含该字符串、一个终止 null 字符 (“\0 ") 和 2 个附加的字节。 函数读取直到支持返回换行符 (CR-LF) 组合的字符或字符指定数目的读取。 该字符串在buffer[2]处开始存储。 如果函数读取 CR-LF,它存储 null 字符 (“\0 ")。 然后,在第二个数组元素buffer[1]中,函数存储该字符串的实际长度。

由于所有编辑键处于活动状态,当 _cgets 或_cgetws 在控制台窗口调用时,按F3 键重复上一次输入的项。

在 C++ 中,这些函数具有模板重载,以调用这些函数的更新、更安全副本。 有关详细信息,请参阅安全模板重载

一般文本例程映射

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 );
   }
}
  

请参见

参考

控制台和端口 I/O

_getch、_getwch