【发布时间】:2013-11-20 05:42:39
【问题描述】:
我试图找出子字符串在字符串输入中重复的次数,但由于某种原因,当我调用该函数时,它给了我一个奇怪的数字。我已经在 main 中测试过这个函数,它工作正常,但是当我创建一个独立函数时它不起作用。
提前谢谢你
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int checkHope(string word1)
{
int answer;
int counter;
for(int i = 0; word1[i] != '\0'; i++)
{
answer = word1.find("h", i);
if ((word1.find("o", (answer+1)) == i+1) && (word1.find("e", (answer+3)) == i+3)) counter++;
}
return counter;
}
int main()
{
string word1;
cout << "Please enter a word to check how many times the word \"hope\" appears. You can also have any letter instead of p.: ";
getline(cin, word1);
cout << checkHope(word1);
return 0;
}
【问题讨论】:
-
尝试将
counter初始化为 0。如果你不这样做,它的开始是随机的。 -
uhuuuu 它有效....多么愚蠢的问题...谢谢@RetiredNinja
标签: c++ string function search