std::gets
From cppreference.com
| ヘッダ <cstdio>で定義 |
||
| char* gets( char* str ); |
(C++11で非推奨) (C++14で削除) |
|
改行文字が見つかるか、またはファイルの終端に達するまで、指定された文字配列にstdinから読み込みます。
目次 |
[編集] 引数
| str | - | 書き込む文字列 |
[編集] 戻り値
成功した場合はstr、失敗した場合はヌルポインタ。
失敗がファイルの終端条件によって引き起こされた場合、さらにstdinのeofインジケータ(std::feof()参照)を設定します。失敗が他のエラーによって引き起こされた場合、stdinのerrorインジケータ(std::ferror()参照)を設定します。
[編集] 注記
std::gets()関数は境界チェックを実行しません。したがって、この関数はバッファオーバーフロー攻撃に対して非常に脆弱です。安全に使用することはできません(プログラムがstdinに表示されるものを制限する環境で実行されない限り)。この理由により、この関数はC++11で非推奨となり、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.
[編集] 関連項目
| stdin、ファイルストリーム、またはバッファから書式付き入力を読み取ります。 (関数) | |
| ファイルストリームから文字列を取得する (関数) | |
| ファイルストリームに文字列を書き込む (関数) | |
| Cドキュメント (gets)
| |