2014-11-14 7 views
0

strlen을 만드는 방법에 대한 예제와 튜토리얼을 찾고 있지만 아무것도 작동하지 않습니다. 나는 문장을 입력 할 수있는 작은 프로그램을 만들고 있으며 문장의 특정 문자를 검색 할 수 있습니다.strlen을 사용하는 중 오류가 발생했습니다.

오류가 읽 sentence 이후

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; 
} 
+0

'strlen' 함수는'std :: string'이 아닌'char *'a.k.a.'char *'C 스타일의 문자열에서 작동합니다. 좋은 C++ 레퍼런스에서 함수 선언과 설명을 검토하십시오. –

답변

4

std::string, 당신은 sentence.length() 또는 strlen(sentence.c_str()) 중 하나를 사용해야합니다.

+1

또는'sentence.size()'(다른 C++ 라이브러리 컨테이너와 일치하기 때문에 선호합니다). 'strlen (sentence.c_str())'은 각 반복의 길이를 계산하는 작업을 수행하기 때문에 좋은 선택이 아닙니다. –

관련 문제