Bhappy
Bhappy

Reputation: 13

Find function in c++

i am trying to find the char a or the char 1 in a string. If they are not found, my program will have a error message and exit. This is my function, however it does not seem to be working. Please help me out, thank you.

*update, if the string is a2, i will get the invalid message, it will only continue if the string is a1.

   bool hasAor1(const std::string& string)
   {
      return string.find_first_of("a1") != std::string::npos;
   }

   //find valid key, key must have numbers like 1234 instead of 134 
   void validstring(string key)
   {
      if(key.length() == 2)
      {
        hasAor1(key) == false;
        cerr << "invalid key";
      }      
   }

Upvotes: 0

Views: 498

Answers (2)

bashrc
bashrc

Reputation: 4835

std::find would be much simpler to use here.

auto iter = find_if(begin(key), end(key),
        [](char v){ return v=='a' || v=='1'; });

if (iter == key.end()) cerr << "invalid key";

Upvotes: 3

DAV
DAV

Reputation: 756

The function hasAor1 is OK.

change the line with "hasAor1(key) == false;' to something like

if (!hasAor1(key)) cerr << "invalid key";

so

   //find valid key, key must have numbers like 1234 instead of 134 
   void validstring(string key)
   {
      if(key.length() == 2)
      {
        if (hasAor1(key) == false)
            cerr << "invalid key";
      }      
   }

It's not clear what validstring is supposed to do. What should it do if the key length is not 2? Shouldn't this be returning a bool or something? As it stands all it will do is print a message but only if the key length is 2. What do you want to happen if the key is "543" or "145" or "1a3"?

The comment in the code "//find valid key, key must have numbers like 1234 instead of 134" doesn't make sense because all of the examples of valid keys contain the character '1' which hasAor1 will mark as invalid.

You may want to think about the possible input variations and what you want to happen for each.

Upvotes: 1

Related Questions