0
所以我的項目是有一個隨機數猜測遊戲(1-100),並將用戶的猜測值存儲到鏈表中。我有的難題是用已存儲在鏈表中的先前輸入檢查用戶的當前輸入。我無法弄清楚爲什麼它會一直告訴我,我真的沒有猜到過以前的數字。正在搜索鏈接的列表C++
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
using namespace std;
struct Guess
{
int numberGuess;
Guess* next;
};
int main()
{
srand(time(0));
Guess* start = 0;
//Defining variables
int randomNumber;
randomNumber = (rand() % 100) + 1;
int userGuess;
int i = 0;
Guess* userValue = new Guess;
cout << "I'm thinking of a number between 1 and 100. Guess what it is: " << endl;
cin >> userGuess;
cin.ignore(1000,10);
userValue->numberGuess = userGuess;
userValue->next = start;
start = userValue;
while(true)
{
if (userGuess > randomNumber)
{
cout << "That's too high, guess again: ";
cin >> userGuess;
cin.ignore(1000,10);
//Pass user's guess to linked based list
Guess* userValue = new Guess;
userValue->numberGuess = userGuess;
userValue->next = start;
start = userValue;
}
else if(userGuess < randomNumber)
{
cout << "That's too low, guess again: ";
cin >> userGuess;
cin.ignore(1000,10);
//Pass user's guess to linked based list
Guess* userValue = new Guess;
userValue->numberGuess = userGuess;
userValue->next = start;
start = userValue;
}
if (userGuess == randomNumber)
{
cout << "Correct!" << endl;
break;
}
//Check to see if it has been guessed
bool checkDuplicate = false;
Guess* p;
for (p = start; p; p = p->next)
{
if (p->numberGuess == userGuess)
{
checkDuplicate = true;
break;
}
}
if (checkDuplicate == true)
{
cout << "You already guessed that value! -- Guess again: ";
cin >> userGuess;
cin.ignore(1000,10);
}
}
}
任何想法?
您將猜測添加到列表(除非是正確的情況除外),然後檢查它是否在列表中。你爲什麼期望檢查失敗? –
爲什麼不使用std :: list? – zoska