<iostream>,cout/cin 未聲明。i 未初始化:迴圈條件 str[i] 使用未定義值,行為未定義。str++ 和索引 i,導致索引與指標不同步。#include <iostream>
#include <cctype> // for isalpha()
using namespace std;
int main() {
cout << \"Please enter a sentence in English: \";
char sentence[500];
cin.getline(sentence, 500);
int count = 0;
for (int i = 0; sentence[i] != '\\0'; ++i) { // 正確:索引遍歷
if (isalpha(static_cast<unsigned char>(sentence[i]))) // 標準庫函數,涵蓋 A-Z, a-z
++count;
}
cout << \"There are \" << count << \" letters in this sentence.\" << endl;
return 0;
}
isalpha() 替代手動範圍判斷,自動處理字符集/區域設置,碼風更專業。static_cast<unsigned char> 避免負值 char 導致未定義行為(C++ 標準要求)。i 在 for 初始化區聲明,作用域最小化。++count 前置遞增,習慣性效能優化(編譯器通常優化相同)。#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main() {
cout << \"Please enter a sentence in English: \";
string sentence;
getline(cin, sentence);
int count = count_if(sentence.begin(), sentence.end(),
[](unsigned char c) { return isalpha(c); });
cout << \"There are \" << count << \" letters in this sentence.\" << endl;
return 0;
}
優勢:無緩衝區大小限制、自動記憶體管理、標準算法可讀性高、易並行化 (std::execution::par)。
**頭文件完整、變數初始化、使用標準庫算法**是 C++ 入門三大鐵律。原始代碼錯誤典型反映「C 風格寫 C++」的習慣問題,建議從 std::string + 算法 起步。