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

C++ count chars in a string

本文关键字:字符 计算 字符串 C++      更新时间:2023-10-16

我需要计算输入句子中输入字符的数量。我离得很近,但是我不断收到此错误:

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;

谁能伸出援手?

没有空字符这样的东西。

只是写

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

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

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

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