2014-11-14 30 views
0

我一直在查找有關如何使strlen工作的示例和教程,但沒有任何工作。我正在製作一個小程序,讓你輸入你的句子,你可以在句子中搜索一個特定的字母。使用strlen的錯誤

錯誤讀取:

19:23: error: cannot convert âstd::string {aka std::basic_string<char>}â to âconst char*â for argument â1â to âsize_t strlen(const char*)â

#include <iostream> 
#include <string> 
#include <cstring> 

using namespace std; 

int main() { 
    char letter; 
    string sentence; 
    int count; 

    cout << "Enter a character to count the number of times it is in a sentence: "; 
    cin >> letter; 

    cout << "Enter a sentence and to search for a specified character: " << endl; 
    getline(cin, sentence); 

    for(int i = 0; i < strlen(sentence); i++){ 
      if(sentence[i] == letter){ 
        count++; 
      } 
    } 
    cout << letter << " was found " << count << " times." << endl; 
} 
+0

'strlen'函數對C風格的字符串a.k.a.'char *'起作用,而不是'std :: string'。在任何優秀的C++參考中查看函數聲明和描述。 –

回答

4

由於sentencestd::string,你應該使用sentence.length()strlen(sentence.c_str())

+1

或'sentence.size()'(我更喜歡它,因爲它符合其他C++庫容器)。 'strlen(sentence.c_str())'不是一個好的選擇,因爲它可能會執行計算每次迭代長度的工作。 –