我需要计算输入句子中输入字符的数量。我很近,但我一直收到这个错误:
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;
任何人都可以伸出援手吗?
答案 0 :(得分:0)
没有空角色。
只需写下
if (sentence == "")
{
cout << "Please enter a valid answer:\n";
break;
}
答案 1 :(得分:0)
在计算之后(请在将来以某种方式标记错误的行)其中一个问题是这一行:
if(character == '' || sentence == "" )
在C ++(和C)中,你不能有空字符文字。
当您阅读character
并且未输入任何内容时,您会收到换行符,因此首次检查应为character == '\n'
。
对于字符串,有一种非常简单的方法可以检查字符串是否为空:std::string::empty
:
sentence.empty()
所以完整的条件应该是
if (character == '\n' || sentence.empty()) { ... }
至于其他错误,确实存在多个错误:首先,声明WordOccurenceCount
接受两个参数,一个字符串和一个整数。然后用三个参数调用它,其中没有一个参数类型正确。
然后在WordOccurenceCount
的定义中,与声明相比,你有不同的论点。
最后,如果要计算某个字符在字符串中的时间,那么您可能需要查看C ++中可用的standard algorithms,尤其是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);
答案 2 :(得分:0)
此代码出现问题:
1. C ++不采用空字符:if(character == '')
2.函数WordOccurrenceCount
中的参数与您的声明不符。
3. sentence.begin()
是String_iterator类型,不能转换为字符串。 (正如您WordOccurrenceCount
函数所期望的那样)
4.同样,sentence.end
也是String_iterator类型,不能转换为int(正如函数声明所预期的那样)或字符串(正如函数定义所预期的那样)。