[英]Compare a string to a list of Ints? C++
我试图让一个字符串只在它与列表中的一个 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)
^这有效,但任何数字都有效,这不是我要找的。
唔。 首先,我不知道为什么您必须输入“字符串”而不是“整数”。 另外,为什么要使“key”成为全局变量? 只要把它放在'main'里面。 此外,'Keys' 是一个数组,您不能将变量与数组进行比较。您必须使用循环搜索数组。
我更喜欢的答案
#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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.