原始錯誤代碼
char str[100];
cin >> str[100]; // 錯誤1:寫入越界,且只讀取單字符
int *p = count(str); // str 未初始化
// count 函數 new int[26] 未 delete
三大錯誤
cin >> str[100]:str[100] 是第 101 個字符(越界),類型為 char,cin 僅讀取一個字符到該位置。正確:cin >> str 或 cin.getline(str, 100)。
count 函數返回 new int[26],調用者未 delete[],造成內存洩漏。
- 未處理大寫字母、非字母字符。
現代 C++ 正確實現
#include <iostream>
#include <string>
#include <array>
#include <cctype>
int main() {
std::string input;
std::getline(std::cin, input); // 讀取整行,含空格
std::array freq = {0}; // 棧上分配,自動釋放
for (char c : input) {
if (std::isalpha(static_cast(c))) {
freq[std::tolower(c) - 'a']++;
}
}
for (int i = 0; i < 26; ++i) {
if (freq[i] > 0) {
std::cout << char('a' + i) << ": " << freq[i] << " times\n";
}
}
return 0;
}
改進點
- 使用
std::string 避免緩衝區溢出。
std::array 替代裸指針,RAII 自動管理內存。
std::isalpha/std::tolower 處理大小寫與非字母。
- 範圍 for 循環簡潔安全。