使用strlen时出错

时间:2014-11-14 01:30:51

标签: c++ string 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;
}

1 个答案:

答案 0 :(得分:4)

由于sentencestd::string,您应该使用sentence.length()strlen(sentence.c_str())