Passing a struct with strings

I'm trying to write a code which takes a string and looks for one of three phrases in said line, then returns a string based on the results. Each line contains no more than 1 of the three phrases ('xyz', 'abc', or '123'). I'm trying to figure out why the function isn't working. I get stuck in an infinite loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 string Findphrase (string line)
{
	for (std::string::iterator it=line.begin(); it!=line.end(); ++it)
	{
		if((*it == 'x') && (*(it+1) == 'y') && (*(it+2) == 'z'))
		{
			return "option 1";
		} 
		else if((*it == 'a') && (*(it+1) == 'b') && (*(it+2) == 'c'))
		{
			return "option 2";
		}
		else if((*it == '1') && (*(it+1) == '2') && (*(it+2) == '3'))
		{
			return "option 3";
		}
		else
		{
			return "N/A";
		}
	}
}
I don't know why you are getting infinite loop, but a few things that I can spot are:

1. You should check that the length of the string line is atleast equal to 3. Only then enter the for loop.

2. Iterate only till line.end() - 3 (it + 2 != line.end())

3. Move the last else (return "N/A") out of the for loop.

An easier option is to try using the built-in search algorithm
http://www.cplusplus.com/reference/algorithm/search/
Your code is invalid. It would be simpler and better to write

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
string Findphrase( const string &line )
{
	if ( line == "xyz" )
	{
		return "option 1";
	} 
	else if ( line == "abc" )
	{
		return "option 2";
	}
	else if ( line == "123" )
	{
		return "option 3";
	}
	else
	{
		return "N/A";
	}
}

Topic archived. No new replies allowed.