【发布时间】:2013-11-12 12:53:40
【问题描述】:
我需要计算输入句子中输入字符的数量。我是如此接近,但我不断收到此错误:
countchar.cpp:19:19: error: empty character constant
countchar.cpp: In function â:
countchar.cpp:26:75: error: could not convert â from â to â
#include <string>
#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;
void WordOccurenceCount(string, int);
int main()
{
char character;
string sentence;
char answer;
string cCount;
while(1) {
cout << "Enter a char to find out how many times it is in a sentence: ";
cin >> character;
cout << "Enter a sentence and to search for a specified character: ";
cin >> sentence;
if(character == '' || sentence == "" )
{
cout << "Please enter a valid answer:\n";
break;
}
else {
cCount = WordOccurenceCount(sentence.begin(), sentence.end(), character);
cout << "Your sentence had" << cCount << character
<< "character(s)";
}
cout << "Do you wish to enter another sentence (y/n)?: ";
cin >> answer;
if (answer == 'n'){
break;
}
}
return 0;
}
int WordOccurrenceCount( string const & str, string const & word )
{
int count;
string::size_type word_pos( 0 );
while ( word_pos!=string::npos )
{
word_pos = str.find(word, word_pos );
if ( word_pos != string::npos )
{
++count;
// start next search after this word
word_pos += word.length();
}
}
return count;
有人可以帮忙吗?
【问题讨论】:
-
您的标题和问题显示“count chars”,但您的代码看起来像是在计算 words?
-
您的意思是某些文本中“字符串”的数量?或字符串中的字符数??
-
@ArneMertz 您发布的线程与 Java 而非 C++ 相关
-
@stellarossa 刚刚注意到,谢谢。所以这里有其他人:stackoverflow.com/questions/7363257/…,stackoverflow.com/questions/8870263/…