User Defined Functions


string checker, that is passed a string and a character, and checks if the character is
within the string. If it is, it returns an integer of the index it is at. If it is not, it returns ‐1.
how can i do this?
Last edited on
Hello samaka,

What have you done so far?

http://www.cplusplus.com/reference/string/string/

Look at the "find" and "find_first_of" functions.

Andy
The string has a method find: http://www.cplusplus.com/reference/string/string/find/
If the character isn't in the string you will receive the value string::npos, you just return -1 instead.
Hi thank you both but i still dont know if i did the return -1 part properly can i have your ideas? thank you :)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
	cout << "whats your Word? ";
	cin >> s;
	cout << "whats the letter you wanna find in your word :) " << endl;
	char letter;
	cin >> letter;
	if (s.find(letter))
	{
		cout << s.find(letter) << endl;
	}
	else 
	{
		return -1;
	}
	return 0;
  
I think you need to put your code in a function like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
int in_string(const string& input, char ch)
{
  string::size_type idx = input.find(ch);
  if( idx== string::npos)
  {
     return -1;
  }
  else
  {
     // int and string::size_type are different so we need to cast it
     return static_cast<int>(idx);
  }
}

In main you get the input, call the function and print the result
1
2
3
4
5
int in_String( const string &str, char ch )
{
   for ( int i = 0; i < str.size(); i++ ) if ( str[i] == ch ) return i;
   return -1;
}
thanks everone i got the idea :)
Topic archived. No new replies allowed.