gpt4 book ai didi

C++ 计算字符串中的字符数

转载 作者:太空宇宙 更新时间:2023-11-04 15:20:43 26 4
gpt4 key购买 nike

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

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

最佳答案

问题似乎出在这一行:

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

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

至于剩下的错误,你应该使用sentence.begin() 而不是begin(sentence) 和类似的sentence.end() 而不是 end(sentence)

关于C++ 计算字符串中的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19930773/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com