[英]C++ count number of characters in a string
我是如此亲密,我需要计算给定字符串中给定字符的数量。 它需要一遍又一遍地循环,但我不断收到此错误:
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
我确实对count的算法不太熟悉,但是如果有人可以提供帮助,将不胜感激。 这是我的代码:
#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;
}
问题似乎在这一行:
int count = count(begin(sentence), end(sentence), character);
您声明一个变量count
并在将其用作函数后立即声明。 您必须重命名变量(例如c
)才能使用函数std::count
。
至于其余的错误,应使用sentence.begin()
代替begin(sentence)
,类似地使用sentence.end()
代替end(sentence)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.