Error using strlen

2.7k views Asked by At

I have been looking up examples and tutorials on how to make strlen work, but nothing is working. I am making a small program that lets you type your sentence and you can search a specific letter in the sentence.

The error reads:

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

There are 1 answers

1
timrau On BEST ANSWER

Since sentence is a std::string, you should use either sentence.length() or strlen(sentence.c_str()).