我非常接近,我需要计算给定字符串中给定字符的数量。它需要一遍又一遍地循环,但我一直收到这个错误:
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;
}
答案 0 :(得分:7)
问题似乎在于这一行:
int count = count(begin(sentence), end(sentence), character);
您在将其用作函数后立即声明变量count
。您必须重命名变量(例如,c
)才能使用函数std::count
。
至于剩余的错误,您应该使用sentence.begin()
代替begin(sentence)
,而使用sentence.end()
代替end(sentence)
。