首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 統計英文句子字母數量:修正頭文件、變數初始化與迴圈邏輯

     編輯:程式設計綜合問答

原始代碼三大錯誤

  1. 缺少頭文件:未包含 <iostream>,cout/cin 未聲明。
  2. 索引變數 i 未初始化:迴圈條件 str[i] 使用未定義值,行為未定義。
  3. 迴圈邏輯錯誤:同時使用指標 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 前置遞增,習慣性效能優化(編譯器通常優化相同)。

進階:使用 C++ 風格字串與算法

#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 + 算法 起步。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved