Bool function

A function determineLetter should return true if there is only one of "abcdefxyz" letter. But it only works for "a". What's wrong?
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
#include <iostream>
#include <string>
std::string letter = "abcdefxyz";

bool determineLetter (  std::string character, size_t i = 0)
{
	
	if(character.size() != 1){ 
	return false;
   }

	if(character[i] == letter[i]) { 
	return true;
   }
   else return false;
	
	if (i == 9) {
	return false;
   }
	
	return determineLetter( character, i++);
}

int main()
{
	std::string d = "b";
	std::cout << determineLetter ( d, 0) << std::endl; // returns FALSE but i expected TRUE
	return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
#include <string>

// return true if there is only one of the characters in searched_letters
// (default: only one of "abcdefxyz" )
bool determineLetter( const std::string& str, const std::string& searched_letters = "abcdefxyz" )
{
    // https://en.cppreference.com/w/cpp/string/basic_string/find_first_of
    const auto pos = str.find_first_of(searched_letters) ;

    return ( pos != std::string::npos ) // return true if 1. we found the first one
           && ( str.find_last_of(searched_letters) == pos ) ; // and 2. it is the only one
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
using namespace std;

bool containsOneLetter( const string &str, const string &letters )
{
   size_t pos;   	
   return ( ( pos = str.find_first_of( letters ) ) != str.npos && str.find_first_of( letters, pos + 1 ) == str.npos );
}

int main()
{
   const string letters = "abcdefxyz";
   cout << boolalpha << containsOneLetter( "cplusplus", letters ) << '\n';
   cout << boolalpha << containsOneLetter( "cplusplus.com", letters ) << '\n';
}
Topic archived. No new replies allowed.