Why does this code not work?

I just cracked up some code to check how many occurrences of a string are found in another string... It is self-explanatory:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>

using namespace std;

int occur(string li, string lf);

int main()
{
	cout << "Please enter string to find occurences: ";
    string nput;
	cin >> nput;
	cout << "Occurences to search for: ";
	string occ;
	cin >> occ;
	cout << occur(nput,occ);
	return 0;
}

int occur(string li, string lf)
{
    int counter = 0;
	while (li.find(lf) != string::npos)
	{
	    int p = li.find(lf);
	    int l = p + lf.length() - 1;
	    for (p = p; p <= l; p++)
	    {
		    li[p] = static_cast<char>(8);
	    }
	    ++counter;
    }
}

The program does compile, but it runs completely wrong here is a sample run:
Please enter string to find occurences: aaabbbcc
Occurences to search for: c
-256
There's no return statement in the occur function - looks like you meant to return an integer value?

Edit: Doesn't look like it's getting into the while loop. cin stops at blank spaces. If you want someone to be able to enter more than one word - check into using getline instead of cin.
Last edited on
I don't know what to say, I have rosy cheeks now (for the return statement. As for the second point, I currently don't need to be able to input string with whitespace...
Topic archived. No new replies allowed.