我试图让只有与列表中的int匹配的字符串才能工作。
代码
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
}
}
我尝试四处搜索,但找不到任何有效方法。我确实尝试过
if (sscanf(key.c_str(), "%d", &Keys) == 1)
^这有效,但是任何数字都有效,这不是我想要的。
答案 0 :(得分:0)
嗯。首先,我不知道为什么您必须输入“字符串”而不是“ int”。另外,为什么要使“键”成为全局变量?只需将其放入“ main”中即可。而且,“键”是一个数组,不能将变量与数组进行比较。必须使用循环在数组中进行搜索。
我喜欢的答案
#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
}