Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

C++ count chars in a string

I need to count the number of an input character there is in an input sentence. I am so close however I keep getting this error:

countchar.cpp:19:19: error: empty character constant
countchar.cpp: In function a:
countchar.cpp:26:75: error: could not convert a from a to a



#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:
";
            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;

Can anyone lend a hand?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There's no such thing as an empty character.

Just write

if (sentence == "")
{
        cout << "Please enter a valid answer:
";
        break;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...