std::gets
來自 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
|