#include <string>
#include <iostream>
using namespace std;
int main() {
string ch;
char *p = &ch[0];
gets(p);
cout << ch << endl;
system("pause");
return 0;
}
在 VS2012 中運行上述代碼,程序無法通過 gets(p) 正常接收鍵盤輸入的字符串。
string ch; 默認構造為空字符串,內部緩衝區大小為 0&ch[0] 返回的是首字符引用,但空字符串無有效字符存儲空間cout << ch 輸出的是 string 對象本身,而非字符指針gets,應配合字符數組而非 string 內部緩衝區#include <string>
#include <iostream>
using namespace std;
int main() {
string ch;
cout << "請輸入字符串: ";
getline(cin, ch); // 安全、自動管理內存、支持空格
cout << "輸入內容: " << ch << endl;
system("pause");
return 0;
}
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
char buffer[256] = {0}; // 固定大小緩衝區
cout << "請輸入字符串: ";
fgets(buffer, sizeof(buffer), stdin); // 安全讀取,包含換行符
// 移除末尾換行符
buffer[strcspn(buffer, "\n")] = '\0';
cout << "輸入內容: " << buffer << endl;
system("pause");
return 0;
}
#include <string>
#include <iostream>
#include <cstdio> // gets 需要此頭文件
using namespace std;
int main() {
string ch;
ch.resize(255); // 關鍵:預分配足夠空間
char *p = &ch[0];
gets(p); // 仍不安全,僅演示
cout << ch << endl; // 正確輸出 string 對象
system("pause");
return 0;
}
| 場景 | 推薦函數 | 優點 |
|---|---|---|
| C++ 字符串輸入 | std::getline(cin, str) | 類型安全、自動擴容、支持空白字符 |
| C 風格字符數組 | fgets(buf, size, stdin) | 可控緩衝區大小、標準庫函數 |
| 格式化輸入 | cin >> var / scanf(fmt, &var) | 適合非空白分隔的數據 |
核心原則:現代 C++ 開發中完全避免使用 gets(),優先選擇 std::string 配合 std::getline,兼顧安全性與便利性。