Getting errors for IndexOf function

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
#include "stdafx.h"
#include <iostream>
#include <string>
#include <locale>

using namespace std;

int IndexOf(string& text, string& pattern)
{
	// where appears the pattern in the text?
	string::size_type loc = text.find(pattern, 0);
	if (loc != string::npos)
	{
		return loc;
	}
	else
	{
		return -1;
	}
}

int main(array<System::String ^> ^args)
{
	string s = "Text";

	//  returns 1 because 'ext' is on the position 1 in s
	int index = IndexOf(s, "ext");

	// returns -1 because 'ABC' is not in s
	int index = IndexOf(s, "ABC");

	// returns 2 because 'xt' is on the position 2 in s
	int index = IndexOf(s, "xt");
	cin.get();
    return 0;
}


Getting an error on the "ext", "ABC" and "xt" bits. It's basically giving me one of those underlined red squiggly lines and I'm not sure why it is happening.

Also, what is "string::size_type" used for as well as "string::npos" used for in this code?
Last edited on
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
#include <iostream>
#include <string>

using namespace std;

int IndexOf(string& text, string& pattern)
{
	// where appears the pattern in the text?
	string::size_type loc = text.find(pattern, 0);
	if (loc != string::npos)
	{
		return loc;
	}
	else
	{
		return -1;
	}
}

int main()
{
	string s = "Text", pattern="ext";

	//  returns 1 because 'ext' is on the position 1 in s
	int index = IndexOf(s, pattern);
        cout<<index<<endl;
        pattern="ABC";
	// returns -1 because 'ABC' is not in s
	index = IndexOf(s, pattern);
        cout<<index<<endl;
	// returns 2 because 'xt' is on the position 2 in s
        pattern="xt";
	index = IndexOf(s, pattern);
        cout<<index<<endl;
    return 0;
}

The major thing my compiler found are that you redeclare index on your lines 30 and 33, and "
Line 26: error: invalid initialization of non-const reference of type 'std::string&' from a temporary of type 'const char*'".
Thanks man.
Topic archived. No new replies allowed.