如何检查cin是否与数组中的一组数字匹配

How to check if cin matches a set of numbers in an array?

本文关键字:一组 数字 何检查 检查 cin 是否 数组      更新时间:2023-10-16

此代码从1-6生成5个随机数。然后,它将数字存储到一个包含5个数字的数组中。然后,它会提示用户输入这五个数字。如何检查"cin"是否与数组中的数字匹配?

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <windows.h>
using namespace std;
int magicNumbers;
int code;
int array[5];
void enterCode()
{
cout << "nnnnEnter your given code: ";
cin >> code;
if(code == array[])
{
cout << "Yes!";
}
else if(code != array[])
{
cout << "No!";
}
}
int main()
{
srand(time(NULL));
for(int x = 0; x < 5; x++)
{
magicNumbers = 1+rand()%6;
array[x] = magicNumbers;
cout << magicNumbers << endl;
}
cout << "nThe Array" << endl;
cout << "-----------------" << endl;
cout << array[0] << array[1] << array[2] << array[3] << array[4];
Sleep(2000);
enterCode();
return 0;
}

您可以通过创建第二个数组来分别询问用户代码的每个数字,并用用户的输入填充。然后将每个数组一次比较一项。

如果你仍然想一次要求所有代码,你需要将代码的每个数字分割成一个数组:-可以使用字符串流将数字转换为字符串,然后逐字符拆分-你可以直接拆分数字,例如使用这里描述的技术:C:如何将多位数拆分为单独的变量?