I don't get why my .find function don't work

Viewed 49

I have a problem with this code. My if statement for userInput.find("=") is always true :

std::string userInput;
while (1)
{
  std::cout << "> ";
  getline(std::cin, userInput);
  if (std::cin.eof())
  {
    std::cout << "Program Exit" << std::endl;
    return 0;
  }
  if (userInput == "exit")
  {
    std::cout << "Program exit" << std::endl;
    return 0;
  }
  if (userInput.find("="))
  {
    std::cout << "yes" << std::endl;
  }
}

output :

./main
> print a
yes
> exit
> Program Exit

But I don't see any "=" in my "print a" sentence

2 Answers

Read the reference for std::string.find. http://www.cplusplus.com/reference/string/string/find/

Note it says it returns the position of the query, or if none, returns string::npos, which if you follow through will see string::npos = -1 = SIZE_MAX. (this is the only un-used number in the size_t number space, as a string might have indices all the way from 0 up to SIZE_MAX-1) Any non-zero integer coerces to true, so your statement will always be true.

Change to check if find != string::npos.

userInput.find() does not return a bool. It will return npos if it does not find it, and your check will construct a boolean from npos, which will be TRUE.

Answer: check for npos explicitly

Related