用戶嘗試用 char[] 和 string 分別實現相同功能,但 string 版本編譯報錯或運行異常。
// 錯誤嘗試:對 string 使用 cin.getline
string name;
name.resize(20); // 僅設置大小,不改變內部緩衝區指針
cin.getline((char*)name.c_str(), 20); // 錯誤!c_str() 返回 const char*,不可修改
// 強制轉型 (char*) 導致未定義行為,可能崩潰
#include <iostream>
#include <string>
using namespace std;
int main() {
string name, dessert;
cout << "Enter your name:\n";
getline(cin, name); // 標準 C++ 讀取整行
cout << "Enter your favorite dessert:\n";
getline(cin, dessert);
cout << "I have some delicious " << dessert
<< " for you, " << name << ".\n";
return 0;
}
#include <iostream>
using namespace std;
int main() {
const int SIZE = 20;
char name[SIZE], dessert[SIZE];
cout << "Enter your name:\n";
cin.getline(name, SIZE);
cout << "Enter your favorite dessert:\n";
cin.getline(dessert, SIZE);
cout << "I have some delicious " << dessert
<< " for you, " << name << ".\n";
return 0;
}
#include <iostream>
#include <string>
#include <cstring> // strcpy
using namespace std;
int main() {
const int SIZE = 20;
char name[SIZE], dessert[SIZE];
string sName, sDessert;
// char[] 輸入
cout << "Enter name (char[]):\n";
cin.getline(name, SIZE);
sName = name; // 隱式轉換 char* -> string
// string 輸入
cout << "Enter dessert (string):\n";
getline(cin, sDessert);
strncpy(dessert, sDessert.c_str(), SIZE-1); // 反向複製
dessert[SIZE-1] = '\0';
// 輸出驗證
cout << "char[] name: " << name << endl;
cout << "string name: " << sName << endl;
cout << "char[] dessert: " << dessert << endl;
cout << "string dessert: " << sDessert << endl;
return 0;
}
| 操作 | string 正確方法 | char[] 正確方法 |
|---|---|---|
| 讀取整行 | getline(cin, str) | cin.getline(arr, size) |
| 字符串複製 | s1 = s2 | strcpy(des, src) / strncpy |
| 轉換關係 | string s = char_arr / s.c_str() (const char*) | strcpy(arr, s.c_str()) |
| 長度獲取 | s.length() / s.size() | strlen(arr) |
(char*)name.c_str() 是錯誤的?c_str() 返回 const char*,指向 string 內部只讀緩衝區。const 並寫入,違反 C++ 類型安全,可能導致程序崩潰、數據損壞或安全漏洞。resize() 僅改變邏輯長度,不保證底層緩衝區可寫或足夠大。不要嘗試對 std::string 使用 C 風格輸入函數。兩套體系各有專用 API,混用需通過正確轉換(賦值、c_str()、strcpy)完成。教學中建議分開演示,避免混淆。