当前位置:主页 > 游戏攻略 > gets c++中的用法详解

gets c++中的用法详解

文章来源:www.cnqiqu.com 作者:启趣网 发布时间:2025-04-27 00:19

Get a line from the stdin stream. These functions are deprecated because more secure versions are available; see gets_s, _getws_s.

char *gets(

char *buffer

);

wchar_t *_getws(

wchar_t *buffer

);

template <size_t size>

char *gets(

char (&buffer)[size]

); // C++ only

template <size_t size>

wchar_t *_getws(

wchar_t (&buffer)[size]

); // C++ only

Parameters

buffer

Storage location for input string.

Return Value

Returns its argument if successful. A NULL pointer indicates an error or end-of-file condition. Use ferror or feof to determine which one has occurred. If buffer is NULL, these functions invoke an invalid parameter handler, as described in Parameter Validation. If execution is allowed to continue, these functions return NULL and set errno to EINVAL.

Remarks

The gets function reads a line from the standard input stream stdin and stores it in buffer. The line consists of all characters up to and including the first newline character ('\n'). gets then replaces the newline character with a null character ('\0') before returning the line. In contrast, the fgets function retains the newline character. _getws is a wide-character version of gets; its argument and return value are wide-character strings.

Security Note

Because there is no way to limit the number of characters read by gets, untrusted input can easily cause buffer overruns. Use fgets instead.

In C++, these functions have template overloads that invoke the newer, secure counterparts of these functions. For more information, see Secure Template Overloads.

Generic-Text Routine Mappings

TCHAR.H routine _UNICODE & _MBCS not defined _MBCS defined _UNICODE defined

_getts

gets

gets

_getws

Requirements

Routine Required header Compatibility

gets

<stdio.h>

ANSI, Windows 95, Windows 98, Windows 98 Second Edition, Windows Millennium Edition, Windows NT 4.0, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003

_getws

<stdio.h> or <wchar.h>

ANSI, Windows 95, Windows 98, Windows 98 Second Edition, Windows Millennium Edition, Windows NT 4.0, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003

For additional compatibility information, see Compatibility in the Introduction.

Example

Copy Code

// crt_gets.c

// compile with: /W1

#include <stdio.h>

int main( void )

{

char line[21]; // room for 20 chars + '\0'

gets( line ); // C4996

// Danger: No way to limit input to 20 chars.

// Consider using gets_s instead.

printf( The line entered was: %s\n, line );

}

  • 热门攻略