我對這個站點(和一般編程)相對較新,所以如果這篇文章像最後一篇那樣糟糕,請告訴我是否應該改變它,我會盡力做到這一點。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,我完全可以讀取兩列文本,並將它們存儲爲變量的名字和姓氏。相信我,只是忽略那部分。我只在用星號表示的部分存在問題。 –