2017-02-20 44 views
1
#include <iostream> 
using namespace std; 

int countLetters(char text[], char letter); 

int main() 
{ 
    char letter; 
    cout << "Enter a letter: "; 
    cin >> letter; 
    cin.ignore(); 
    char text[1024]; 
    cout << "Enter text: "; 
    cin.getline(text, 1024); 
    int letterCount = countLetters(text, letter); 
    cout << "Number of '" << letter << "'s: " << letterCount << endl; 

    return 0; 
} 

int countLetters(char text[], char letter) 
{ 
    int letterCount = 0; 

    for (int i = 0; i <= text[i]; i++) 
    { 
     if (letter == text[i]) 
     letterCount++; 
    } 

    return letterCount; 
} 

這段代碼的寫法是爲了讓用戶首先詢問他們想要在一行文本中搜索的字母。其次,它會要求用戶輸入他們想要搜索的文本行。最後,它會吐出他們輸入的特定文本行中有多少個字母。元素計數問題

我的具體錯誤在於:當用戶在「CS 124 - 軟件開發簡介」中詢問'e'時,程序只聲明有一個'e'。我不確定什麼是錯誤的,因爲當你運行程序並輸入'o'而要求搜索完全相同的文本行時,你會得到正確數量的'o'值返回,4. 任何關於我的想法錯誤是爲什麼它在搜索'e'時出現問題?

+5

你'for'條件是錯誤的,'for'循環應該繼續,直到它是不太等於'文本''長度不是'text [i]'的值。既然這是C++,你應該使用'string's而不是字符數組,爲什麼要讓它更難? –

+3

什麼是我應該測試的文本? –

+0

嘿傢伙,謝謝你的提示!我建立在Jonathan Wakely和Jonny Henly的建議之上,並且在字母計數函數中,我將「for(int i = 0; i <= text [i]; i ++)」改爲「for(int i = 0; text [i]; i ++),代碼現在適用於「CS 124 - 引入軟件開發」並計算e's! – Jeffery

回答

2

您的for條件有誤,for循環應該繼續,而i小於text的長度不是text[i]的值。既然這是C++,你應該使用string而不是字符數組,爲什麼要讓自己更難?

下面的代碼是C++方法,請注意,我的C++有點生疏,代碼可能包含錯誤。

#include <iostream> 
#include <string> 

using namespace std; 

int countLetters(string text, char letter); 

int main() { 
    char letter = ' '; 
    string text; 

    cout << "Enter a letter: "; 
    cin >> letter; 
    cin.ignore(); 

    cout << "Enter text: "; 
    getline(cin, text); // use 'getline(cin, text)' instead of 'cin >> text' 

    int letterCount = countLetters(text, letter); 
    cout << "Number of '" << letter << "'s: " << letterCount << endl; 

    return 0; 
} 

int countLetters(string text, char letter) { 
    int letterCount = 0; 

    for (int i = 0; i < text.size(); i++) { 
     if (letter == text[i]) { 
      letterCount += 1; 
     } 
    } 

    return letterCount; 
} 
+0

很好的答案,除了字符串文本(「」);'。爲什麼不使用默認構造函數?爲什麼用一個需要用'strlen'來計算的字符串進行初始化,並決定是否分配內存來保存它,當你想要一個空字符串(它將被用戶輸入覆蓋)。 –

+0

好吧,我把這一切都放在那裏,並且對於(int i = 0; i <= text.size())來說,計數器實際上在第一個單詞的末尾停止計數。我輸入字母「o」和單獨的輸入「青蛙」和「froog」,它按照預期計數1和2。但是,當我輸入「o」然後「青蛙跳過沼澤」時,它只在第一個單詞中計算o。 – Jeffery

+0

@JonathanWakely自從我編寫了任何C++代碼以來,我一直在尋找CppReference的'string'頁面,並認爲'string str(「」)'是創建字符串的新規範。我會更新我的答案。 –

0

變化condction

i <= text[i] 

text[i] != '\0'