我一直在查找有關如何使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;
}
'strlen'函數對C風格的字符串a.k.a.'char *'起作用,而不是'std :: string'。在任何優秀的C++參考中查看函數聲明和描述。 –