我一直在查找关于如何使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;
}发布于 2014-11-14 01:33:47
因为sentence是std::string,所以您应该使用sentence.length()或strlen(sentence.c_str())。
https://stackoverflow.com/questions/26921530
复制相似问题