Namespaces
Variants

std:: gets

From cppreference.net
< cpp ‎ | io ‎ | c
헤더 파일에 정의됨 <cstdio>
char * gets ( char * str ) ;
(C++11에서 사용 중단됨)
(C++14에서 제거됨)

개행 문자를 찾거나 파일 끝에 도달할 때까지 주어진 문자 문자열로 stdin 을 읽어들입니다.

목차

매개변수

str - 기록될 문자열

반환값

str 성공 시, 실패 시 널 포인터.

실패가 파일 끝 조건에 의해 발생한 경우, 추가적으로 eof 지시자를 설정합니다( std::feof() 참조). 이는 stdin 에 적용됩니다. 실패가 다른 오류에 의해 발생한 경우, error 지시자를 설정합니다( std::ferror() 참조). 이는 stdin 에 적용됩니다.

참고 사항

std::gets() 함수는 경계 검사를 수행하지 않습니다. 따라서 이 함수는 버퍼 오버플로우 공격에 매우 취약합니다. 안전하게 사용할 수 없습니다( stdin 에 나타날 수 있는 내용을 제한하는 환경에서 프로그램이 실행되지 않는 한). 이러한 이유로 이 함수는 C++11에서 사용 중단(deprecated)되었고 C++14에서 완전히 제거되었습니다. std::fgets() 를 대신 사용할 수 있습니다.

예제

#include <array>
#include <cstdio>
#include <cstring>
int main()
{
    std::puts("Never use std::gets(). Use std::fgets() instead!");
    std::array<char, 16> buf;
    std::printf("Enter a string:\n>");
    if (std::fgets(buf.data(), buf.size(), stdin))
    {
        const auto len = std::strlen(buf.data());
        std::printf(
            "The input string:\n[%s] is %s and has the length %li characters.\n",
            buf.data(), len + 1 < buf.size() ? "not truncated" : "truncated", len
        );
    }
    else if (std::feof(stdin))
    {
        std::puts("Error: the end of stdin stream has been reached.");
    }
    else if (std::ferror(stdin))
    {
        std::puts("I/O error when reading from stdin.");
    }
    else
    {
        std::puts("Unknown stdin error.");
    }
}

가능한 출력:

Never use std::gets(). Use std::fgets() instead!
Enter a string:
>Living on Earth is expensive, but it does include a free trip around the Sun.
The input string:
[Living on Earth] is truncated and has the length 15 characters.

참고 항목

표준 입력, 파일 스트림 또는 버퍼로부터 형식화된 입력을 읽어들임
(함수)
파일 스트림으로부터 문자열을 가져옴
(함수)
파일 스트림에 문자열을 기록함
(함수)
C 문서 for gets