将字符串与 Int 列表进行比较? C++
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)
^这有效,但任何数字都有效,这不是我要找的。
嗯。首先,我不知道你为什么要输入 'string' 而不是 'int'。另外,为什么要使 'key' 成为全局变量?把它放在'main'里面就行了。此外,'Keys' 是一个数组,您不能将变量与 array.You 进行比较,必须使用循环搜索数组。
我的首选答案
#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
}
我试图让一个字符串只有在它与列表中的一个 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)
^这有效,但任何数字都有效,这不是我要找的。
嗯。首先,我不知道你为什么要输入 'string' 而不是 'int'。另外,为什么要使 'key' 成为全局变量?把它放在'main'里面就行了。此外,'Keys' 是一个数组,您不能将变量与 array.You 进行比较,必须使用循环搜索数组。
我的首选答案
#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
}