-2

I'm trying to have a string only work if it matches an int in the list.

Code

int Keys[] = { 23454563, 1262352, 634261253, 152352 };
string key;

int main()
{
    cout << ("Please Enter Key: ");
    cin >> key;

    if (key = Keys)
    {
        //Activate Code
    }
    else
    {
        //Don't activate
    }
}

I've tried searching around and I can't find any valid methods. I did try

if (sscanf(key.c_str(), "%d", &Keys) == 1)

^this works, but any number works and that isn't what I'm looking for.

Ok I See
  • 23
  • 4

1 Answers1

0

hmm. First, I don't know why you have to input a 'string' instead of an 'int'. Also, why do you make 'key' a global variable? Just put it inside 'main'. Moreover, 'Keys' is an array and you can't compare a variable with an array.You have to search through the array using a loop.

My prefer answer

#include <iostream>

int main()
{
  
  constexpr int Keys[] { 23454563, 1262352, 634261253, 152352 };

  int key; 
  bool isNumberMatched {false};
  std::cout << ("Please Enter Key: ");
  std::cin >> key;
   
  for (auto number : Keys) //Search through Keys array
     {
       if (key == number)
         isNumberMatched = true;
         break;
     }
  if (isNumberMatched)
     //Activate Code
  else
     //Don't activate
}