[英]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.