我有一个家庭作业,我必须根据空格的数量返回字符串中的单词数量。这是我的代码,我不确定它有什么问题,但是当我尝试编译它时,我不断收到错误消息。
string getWordCount(string sentence){
int count = 1;
for(int i = 1; i < sentence.length(); i++){
if (s[i]==' '){
count++;
}
}
return count;
}
错误信息是:
error: ‘s’ was not declared in this scope
if (s[i]==' '){
^
error: could not convert ‘count’ from ‘int’ to ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’
return count;
^~~~~
最佳答案
要编译您的代码,您必须确保返回类型(count
是一个int
)与声明的函数返回类型兼容(您说它会返回字符串
)。所以不是:
string getWordCount(string sentence)
将您的函数声明为:
int getWordCount(string sentence)
另请注意,您使用了 s[i]
,但未声明 s
。您可能是指 sentence[i]
。
还要考虑解决评论中提到的不同算法错误(即空字符串的错误结果,只有空白的字符串的错误结果,以及根据练习叙述,两个单词之间使用多个连续空格的字符串的错误结果)完成作业并提高技能。
关于c++ - 计算空格以获得字数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48845254/