【发布时间】:2014-11-14 01:30:50
【问题描述】:
我一直在查找有关如何使 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 风格的字符串,也就是char *,不适用于std::string。查看任何好的 C++ 参考中的函数声明和描述。