我对这个站点(和一般编程)相对较新,所以如果这篇文章像最后一篇那样糟糕,请告诉我是否应该改变它,我会尽力做到这一点。C++尝试创建随机排列的密码阵列
因此,我给出了一个阵列密码中的50个密码数组,我面临的直接挑战是必须随机化他们的安排,随机数字发生器的帮助。出于某种原因,使用我所拥有的代码,我在某处犯了一些错误,导致代码被卡在循环中或其他东西中。我知道我接近正确,但我不知道我犯了什么错误。
我试着创建一个随机数,检查它是否已经在数组PasswordsTemp中声明,然后:(如果它已经在数组中,什么都不做),(如果它不在循环中,将它添加到下一个可用索引处的循环中)。为了然后选择另一个随机数,该代码必须循环。我将它设置为循环600次(实际上)确保它在某个时刻猜测每个数字0到50。在此之后,我只是编写了一个简单的cout来查看数组的外观。
任何帮助/意见,将不胜感激。请注意,我在这里比较新,所以也许试着对我稍微容易一些,或者只是帮助其他人代替对我进行指责。谢谢。
#include <iostream>
#include <string>
#include <fstream>
#include <time.h>
int main()
{
std::string firstname = "";
std::string lastname = "";
std::string lastnametemp = "";
std::string fullname = "";
std::string Users[50] = {""};
std::string Passwords[50] = {""};
std::string NewPass = {""};
std::string temp = {""};
int PasswordsTemp[50] = {60};
int randomNumber = 0;
bool repeat = false;
int A = 0;
int i = 0;
std::ifstream inputHandler;
inputHandler.open("names.txt");
while (!inputHandler.eof())//ignore this part. I know it works.
{
inputHandler >> firstname >> lastname; //reads first name and last name of one line
lastnametemp = lastname.substr(0, 7); // sets temp last name as being at most, 7 letters long
fullname = firstname[0] + lastnametemp; // combines the two into a full name
Users[i] = fullname; //creates Users array
i = i + 1;//indexes data
}
std::ifstream indata;
indata.open("passwords.txt");
i = 0;
while (!indata.eof())
{
indata >> Passwords[i];//reads in passwords into array called Passwords
i = i + 1;
}
inputHandler.close();
//*******************************************************
//****************Confusion hereafter********************
//*******************************************************
for (i = 0; i < 600; i++)//Loops a long time to (practically) ensure that all numbers 0 to 50 are guessed atleast once
{
srand(time(NULL));
randomNumber = rand() % 51;//Produces random number between 0 and 50
for (i = 0; i < 51; i++)
{
if (randomNumber == PasswordsTemp[i])
{
repeat = true;//determines if the random number appears anywhere in the PasswordsTemp array; repeat = true if it appears anywhere
}
}
if (repeat == false)//if the random number doesn't appear anywhere, assign the random number an index in Passwordstemp
{
PasswordsTemp[A] = randomNumber;
A = A + 1;
}
}
//*****************************************************************************
//**************************End of Confusion***********************************
//*****************************************************************************
for (A = 0; A < 51; A++)//Checks to see if the passwords are randomized
{
temp = Passwords[PasswordsTemp[A]];
std::cout << temp << std::endl;
}
return 0;
}
'while(!inputHandler.eof())//忽略此部分。我知道它的工作原理。'[它不起作用。](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – user4581301
既不'同时(!indata.eof())'出于同样的原因。 – user4581301
@ user4581301我不知道该告诉你什么。使用我的文件names.txt,我完全可以读取两列文本,并将它们存储为变量的名字和姓氏。相信我,只是忽略那部分。我只在用星号表示的部分存在问题。 –