Hey guys, as I'm googling for help on my issue, I came across a user saying that if I wanted to check if an user input has already been inputted, I'd have to put the user input variable into an array, iterate it through, and check with any current input; and, if positive, I would have to move one element back to continue. How would I go about doing this? Are there similar examples that I can analyze and model off from? If so, please provide the links!
Just for a reference, I'm trying to make a basic number guessing game, where program generates a random number and the user must guess its number.
#include <iomanip>
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
usingnamespace std;
struct Guess
{
int userGuess;
}; //Guess
int main()
{
constint MAX_GUESSES = 100; //list capacity
int nGUESS = 0; // initially empty list
Guess userGuess[MAX_GUESSES]; // the array
//variables
int randomNumber = rand() % 100 + 1; //generating random number
int userinput; //user's input
cout << "Welcome to the Random Number Guessing Game!" << endl;
cout << "Guess a number from [1 - 100] to begin playing! " << endl;
do
{
Guess aGuess; //temporary variable
cin >> userinput; // inputting user input
if (userinput > randomNumber)
{
cout << "That's too high!" << endl;
if (nGUESS < MAX_GUESSES)
{
userGuess[nGUESS++] = aGuess;
} // Adding record to list if it's not full
}// if
elseif (userinput < randomNumber)
{
cout << "That's too low!" << endl;
if (nGUESS < MAX_GUESSES)
{
userGuess[nGUESS++] = aGuess;
} // Adding record to list if it's not full
} // else if
else
{
cout << "That's correct!" << endl;
if (nGUESS < MAX_GUESSES)
{
userGuess[nGUESS++] = aGuess;
} // Adding record to list if it's not full
} // else
//Sorting if user input as been inputted already
for (int i = 0; i < nGUESS; i++)
{
for (int j = i + 1; j < nGUESS; j++)
{
if (userGuess[i].userGuess > userGuess[j].userGuess)
{
Guess temp = userGuess[i];
userGuess[i] = userGuess[j];
userGuess[j] = temp;
if (temp = userinput)
{
cout << "You already guessed that" << endl;
}
}
}
}
}while (userinput != randomNumber); //do
} //main
std::list seems like it would be what you want but it is not - it's actually a poorly named linked list and is generally slower than std::vector (which is also poorly named).
Unfortunately, I can't use the aforementioned shortcuts. My professor won't accept anything "complex" and "to- the-point." I just need a simple model or example of array input validation being used in a code, so I can analyze and model mine after it.
Thanks for the feedback though!
Plain arrays are far more complex and tricky to use than simply using a vector or a set. Has your professor explicitly forbidden using std::vector and std::set? If so, you are effectively asking for C help on a C++ forum.