Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::gets

      From cppreference.com
      <cpp‎ |io‎ |c
       
       
       
       
      Defined in header<cstdio>
      char* gets(char* str);
      (deprecated in C++11)
      (removed in C++14)

      Readsstdin into given character string until a newline character is found or end-of-file occurs.

      Contents

      [edit]Parameters

      str - character string to be written

      [edit]Return value

      str on success, a null pointer on failure.

      If the failure has been caused by end of file condition, additionally sets theeof indicator (seestd::feof()) onstdin. If the failure has been caused by some other error, sets theerror indicator (seestd::ferror()) onstdin.

      [edit]Notes

      Thestd::gets() function does not perform bounds checking. Therefore, this function is extremely vulnerable to buffer-overflow attacks. It cannot be used safely (unless the program runs in an environment which restricts what can appear onstdin). For this reason, the function was deprecated in C++11 and removed altogether in C++14.std::fgets() may be used instead.

      [edit]Example

      Run this code
      #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)){constauto 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);}elseif(std::feof(stdin)){std::puts("Error: the end of stdin stream has been reached.");}elseif(std::ferror(stdin)){std::puts("I/O error when reading from stdin.");}else{std::puts("Unknown stdin error.");}}

      Possible output:

      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.

      [edit]See also

      reads formatted input fromstdin, a file stream or a buffer
      (function)[edit]
      gets a character string from a file stream
      (function)[edit]
      writes a character string to a file stream
      (function)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/io/c/gets&oldid=144183"

      [8]ページ先頭

      ©2009-2025 Movatter.jp