0

我非常接近,我需要计算给定字符串中给定字符的数量。它需要一遍又一遍地循环,但我不断收到此错误:

countchar.cpp:27:22: error: â was not declared in this scope
countchar.cpp:27:38: error: â was not declared in this scope
countchar.cpp:27:61: error: â cannot be used as a function

我真的对计数算法不太熟悉,但如果有人可以提供帮助,那将不胜感激。这是我的代码:

#include <string> 
#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
char character;
string sentence;
char answer;
while(1) {

    cout << "Enter a character to count the number of times it is in a              sentence: ";
    cin >> character;
    cout << "Enter a sentence and to search for a specified character: ";
    getline(cin, sentence);
    if(character == '\n' || sentence.empty())
    {
        cout << "Please enter a valid answer:\n";
        break;

    }


    else {
        int count = count(begin(sentence), end(sentence), character);
        cout << "Your sentence had" << count << character 
             << "character(s)"; 
     }

cout << "Do you wish to enter another sentence (y/n)?: ";
cin >> answer;
if (answer == 'n'){
    break;
    }
}
return 0;
}
4

1 回答 1

7

问题似乎出在这一行:

int count = count(begin(sentence), end(sentence), character);

您声明一个变量count,并在您将其用作函数后立即声明。您必须重命名变量(例如,c)才能使用 function std::count

至于剩下的错误,你应该使用sentence.begin()代替,begin(sentence)类似地sentence.end()代替end(sentence)

于 2013-11-12T13:44:23.437 回答