-3

我需要计算输入句子中输入字符的数量。我很接近但是我不断收到这个错误:

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;

任何人都可以伸出援助之手吗?

4

3 回答 3

0

没有空字符这样的东西。

写吧

if (sentence == "")
{
        cout << "Please enter a valid answer:\n";
        break;
}
于 2013-11-12T12:59:25.303 回答
0

计数后(请在将来以某种方式标记错误的行),其中一个问题是这一行:

if(character == '' || sentence == "" )

在 C++(和 C)中,不能有空字符文字。

当您阅读character并没有输入任何内容时,您会得到换行符,因此第一个检查应该是character == '\n'.

至于字符串,有一个非常简单的方法来检查字符串是否为空std::string::empty::

sentence.empty()

所以完整的条件应该是

if (character == '\n' || sentence.empty()) { ... }

至于其他错误,确实有多个错误:首先,您声明WordOccurenceCount接受两个参数,一个字符串和一个整数。然后你用三个参数调用它,它们都不是正确的类型。

然后在定义中,WordOccurenceCount与声明相比,您有不同的论点。


最后,如果您想计算某个字符在字符串中出现的次数,那么您可能需要查看 C++ 中可用的标准算法,尤其是std::count

std::string sentence;
std::cout << "Enter a sentence: ";
std::getline(std::cin, sentence);

char character;
std::cout << "Enter a character to be found: ";
std::cin >> character;

long count = std::count(std::begin(sentence), std::end(sentence), character);
于 2013-11-12T13:00:42.673 回答
0

此代码的问题:1. C++ 不接受空字符:if(character == '') 2. 函数中的参数WordOccurrenceCount与您的声明不匹配。3.sentence.begin()是String_iterator类型,不能转成字符串。(正如你的WordOccurrenceCount函数所期望的那样) 4. 同样,sentence.end它也是 String_iterator 类型,不能转换为 int (正如你的函数声明所期望的那样)或 string (正如你的函数定义所期望的那样)。

于 2013-11-12T13:11:38.207 回答