A constant function parameter not working, help!

The purpose of this program is to be given 2 strings, and then it looks for string 2 in string one, and returns the pointer of the first occurrence of string 2 in string 1.

ex:
string1: banana
string2: an

'an' (string2) make up the 2nd and 3rd characters of string1 as well as the 4th and the 5th, but since 2nd and 3rd are the first occurrence, then it looks for that. The program finds this and returns a pointer of where string2 is located in string one, in this case, the address of the 2nd character in string 1.

The code works perfectly, as long as string2 is NOT a constant in the function. The problem is that I have to keep it as a constant.

I even tried traveling-pointers as to not change the content of the string but that didn't work either.

What should I do????

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
using namespace std ;

char *strstr(char *str1, const char *str2)
{
	int count2= 0, count2_max= 0 ;

	while (*(str2) != '\0') //recording max value of 2nd string
	{
		str2++ ;
		count2_max++ ;
	}
	str2 -= count2_max ;
	while (*(str1) != '\0') //checking string 1 character by character for if it has string 2 in it.
	{
		if (*(str2) == *(str1))
		{
			str2++ ;
			count2++ ;		
		}
		else
		{
			if (*(str1) != *(str1-1))
			{
				count2= 0 ;	
			}
		}

		if (count2 == count2_max) //checking if 2nd string is complete in the first string
		{
			str1=((str1-count2_max) + 1) ;
			return 	str1 ;
		}
		str1++ ;
	}
	if (*(str1) == '\0')
	{
		return NULL ;
	}
}

void main()
{
	char *str1= new char[100] ; //The first string
	char *str2= new char[100] ; //The second string

	cout << "Please Enter the string: " ; cin.getline(str1, 100) ;
	cout << "Now please enter the second string: " ; cin.getline(str2, 100) ;
	
	cout << endl << "The pointer to the first occured second string (str2) in the first string (str1) holds the following address: " << (int*)strstr(str1, str2) << endl << endl ;

	delete []str1 ;
	delete []str2 ;
}
Last edited on
What do you mean? Your code is working. Show us code you have problem with.
@miinipaa check it now. I added the const to the second parameter of the function and now it doesnt work. How can i make it work while keeping it constant ..??
Topic archived. No new replies allowed.