Checking if input is in the array already, and if its int or not

so I just started learning c++ and I am supposed to make a guessing game between 1-100 in c++ where I need to ask the player's name and store it, need to keep track of the guesses and store them as well, validate if the input a whole number between 1-100, lastly check if the number is already guessed.

I am having some trouble with the last two which are checking if the number is an int between 1-100 and if it's already been guessed, I have tried a few ways but it won't work correctly.

Thanks in advance!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <algorithm>



int main()
{
    char response;

	do
	{
		int guess;

		int number;

		int tries = 0;

		const int min = 0;

		const int max = 100;

		int myArray[99] = {};

		bool check = false;

		std::string playerName;

		srand(unsigned int(time(0)));
		number = rand() % 101;

		std::cout << "Welcome to The Guessing game\ninput your name please: " << std::endl;

		std::getline(std::cin, playerName);

		std::cout << "\nwelcome " << playerName << "!" << std::endl;

		std::cout << "Please enter a number between 0 and 100 please:  \n" << std::endl;

		std::cin >> guess;

		
		myArray[tries++] = guess;
		

		while (check != true)
		{
			if (guess > max || guess < min || std::cin.fail() || std::cin.rdbuf()->in_avail() > 1)
			{

				std::cout << "\nsorry " << playerName << " your guess is outside the range or invalid, please enter an integer between " << min << " and " << max << std::endl;

				std::cin >> guess;

				continue;
			}

			if (guess > number)
			{

				std::cout << "\nThe number guessed is too high, Please enter your guess again:" << std::endl;

				std::cin >> guess;

				myArray[tries++] = guess;

			}

	    

			else if (guess < number)

			{
				std::cout << "\nThe number guessed is too low, Please enter your guess again:" << std::endl;

				std::cin >> guess;
				
				myArray[tries++] = guess;

			}

			
			else if (guess == number)
			{
				std::cout << "\nYour guess is correct! congratulation " << playerName << " you got it in " << tries << " guesses" << std::endl;

				std::cout << "you have guessed : " << std::endl;

				for (int i = 0; i < tries; ++i)
				{
                  std::cout << myArray[i] << std::endl;
				}
				check = true;

				std::cout << "\nwould you like to play again?" << std::endl;

				std::cout << "type Y to play again or press any key to exit : " << std::endl;

				std::cin >> response;

				std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

				std::cin.clear();

			}
		}
	} while (response == 'Y' || response == 'y');

	system("pause");

}
Last edited on
Hello!

I think you figured out already how to check if the guess is between 0 and 100 on line 50.

Also note that your code won't compile because of line 31, try stand(time(NULL)); instead.

Last for checking if the number has already been guessed it's pretty straight forward. You go through your array comparing the current guess to all the previous saved ones.

Hope this helps.
hey, thanks for replying!

I mean yes I did but when I enter a character it starts spamming the output "sorry " << playerName << " your guess is outside the range or invalid, please enter an integer between 0-100" and I don't know why exactly.

about the guess checking, I did try a couple of things but I am pretty sure that I am missing something I tried :

if(myArray[i]=userinput)

and

if (std::find(std::begin(myArray), std::end(myArray), myArray[i]) != std::end(myArray))

the problem is I am using myArray[i] only inside the scope which is for printing the guesses out and it doesn't work if I put it outside, I am sure it might be obvious but I haven't figured it out.

@hoogo,

What do you mean it will not compile. It worked fine for me. Although I tend to use
srand(static_cast<size_t>(time(NULL)));. Look it up "srand" takes an "unsigned int";
void srand (unsigned int seed);. http://www.cplusplus.com/reference/cstdlib/srand/?kw=srand

Hello MJnoob,

hoogo failed to mention that "srand" only need to be done once before the do/while loop.

about the guess checking, I did try a couple of things but I am pretty sure that I am missing something I tried :

if(myArray[i]=userinput)

Right idea, but put it in a for loop to be done after the input of guess.

Your code will work, it is just that you are using the wrong order of things.

before the while loop all you need is:

1
2
3
4
5
6
char response{};  // <--- Needs to be before the do/while loop to be defined before being used in the while condition of the do/while loop.
std::string playerName;

std::cout << "\nwelcome " << playerName << "!" << std::endl;

std::cout << "Please enter a number between 0 and 100 please: ";
You only need to input the player's name once.

Inside the while loop first get the input for guess then use your if statement to validate the number entered. Based on checking two different thing in the if condition [(MIN and MAX) and (!std::cin)] I set up what you had with:
1
2
3
4
5
6
7
8
9
10
11
12
if (guess > MAX || guess < MIN || !std::cin)
{

	std::cout << "\nsorry " << playerName << " your guess is outside the range or invalid,\nplease enter an integer between " << MIN << " and " << MAX << ": ";
	if (!std::cin)
	{
		std::cin.clear();
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
	}

	continue;
}

The added if statement is to keep the "std::cin.ignore" statement from waiting for input if the "std::cin >> guess;" contains only an out of range number.

The "!std::cin" will catch any problem with a failed "std::cin" whereas "std::cin.fail()" may not be the bit that was set and you are not checking the others that might have been set.

What I am use to seeing is something more like:

1
2
3
4
5
6
7
8
9
10
11
12
std::cin >> guess;

while (!std::cin)
{
	std::cout << "\n Entry is not a number. Try again." << std::endl;

	std::cin.clear();
	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.

	std::cout << "Please enter a number between 0 and 100 please: ";
	std::cin >> guess;
}

This way you stay in the while loop until you get a valid number to check and then follow this while loop with the if statement checking for out of range then the for loop to check for duplicate numbers.

With the changes I made one possible put put is:

Welcome to The Guessing game
input your name please: Andy

welcome Andy!

Please enter a number between 0 and 100 please: 50

The number guessed is too high, Please enter your guess again: 25

The number guessed is too high, Please enter your guess again: 24

Your guess is correct! congratulation Andy you got it in 3 guesses
you have guessed :
50
25
24

would you like to play again?
type Y to play again or press any key to exit: y

Welcome back Andy! Let's play a game.

Please enter a number between 0 and 100 please: 50

The number guessed is too high, Please enter your guess again: 25

The number guessed is too high, Please enter your guess again: 12

The number guessed is too low, Please enter your guess again: 18

The number guessed is too low, Please enter your guess again: 21

The number guessed is too low, Please enter your guess again: 24

Your guess is correct! congratulation Andy you got it in 6 guesses
you have guessed :
50
25
12
18
21
24

would you like to play again?
type Y to play again or press any key to exit:


Just for fun I added this to the code:
1
2
3
4
if (firstTime)
	std::cout << "\nWelcome " << playerName << "!\n" << std::endl;
else
	std::cout << "\nWelcome back " << playerName << "! Let's play a game.\n" << std::endl;


What you have can work although it may not be the best way to code it unless you want to rewrite the whole program.

Hope that help,

Andy
Hello @Handy Andy!

I appreciate the help I understood most of it, but I don't want to use a header I just want to have the game in one cpp file and the order is kinda confusing because I don't know which compile first,

I used this before :
1
2
3
4
for ( int i = 0; i < tries; ++i)
{
     std::cout << myArray[i] << std::endl;
}


and its worked for me to store and output the stored guesses but the "int i" only works inside the scope which makes it hard to use myArray[i] outside it so it must be in a written order or in a different kind of loop I am assuming.

is there any way around using a header?

also, I tried using a vector for storing the guesses and using a find function to get the stored guesses to check them if they exist in it but that a bit more complicated, was it better you think?
Last edited on
Hello MJnoob,

Sorry, you lost me with "use a header". I am not sure what you think it means or what you are trying to say.

I am sorry if you received the wrong idea that you should or need to make this a multi file project. The function I mentioned can easily be put in the same file as "main", but if the program flow is right it is not needed.

You are correct in understanding the scope of a for loop in regards to "i", but seeing a piece of code like myArray[i] my first thought is that it is part of a for loop. Just because you have a for loop like for (int i = 0; i < tries; ++i) does not mean that you can not use "i" again for a different for loop because "i" would be in a different scope.

The code you have is usable. Its just not in the right order. I am think something like:

Define variables:
    constant variables,
        constexpr size_t MAXSIZE{ 100 };
        const int MIN = 0;
        const int MAX = 100;
    response and playerName

Seed RNG
Print welcome message

Get player's name

do/while loop

Define variables

Get random number

Print welcome with player's name

Prompt to enter a number

while loop
    get guess
    check for number, the third bit of code I showed you earlier. The "while (!std::cin)"
    check for proper range. This can be combined with above, but easier to understand when separate.
    for loop to check if a number has already been entered

Your code from "if (guess > number)" on works, but I would remove the "std::cin >> guess;" as this is the wrong places to use it.

My attempt at psudeocode. I hope you can understand it.

In the three line defining the constants the first line shows the more updated version, from C++11 on. In simple terms think of "size_t" as another name for "unsigned int". The curly braces {}, or uniform initializer, empty it will initialize the variable to zero or with a number it will initialize the variable to that number.

It is generally accepted that a variable defined as a constant the variable name is in all caps.

If you rearrange your code like the pseudocode it will work all in one file.

Hope that helps,

Andy
oh yes, I thought you meant I have to make a header for that method, yes thank you! you have cleared things up for me very nicely, sorry if I sound clueless sometimes it's mostly because I just started learning the basics and I am trying to understand how things work to move on to harder things so any helpful tips would be appreciated.

anyway, about the code, I think I figured out how to put it together although I faced few problems like if the number is outside the range it just spams the message and I have to close it and debug again, also the part where you said :
but I would remove the "std::cin >> guess;" as this is the wrong places to use it.

isn't this the only way for me to make sure I am saving the guesses using the next line?

myArray[tries++] = guess;

here is what i did so far :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <algorithm>



int main()
{
    char response;

	do
	{
		int guess;

		int number;

		int tries = 0;

		const int min = 0;

		const int max = 100;

		int myArray[99] = {};

		bool check = false;

		int i;

		std::string playerName;

		srand(unsigned int(time(0)));
		number = rand() % 101;

		std::cout << "Welcome to The Guessing game\ninput your name please: " << std::endl;

		std::getline(std::cin, playerName);

		std::cout << "\nwelcome " << playerName << "!" << std::endl;

		std::cout << "Please enter a number between 0 and 100 please:  \n" << std::endl;

		std::cin >> guess;

		myArray[tries++] = guess;

		
		/*for (int i = 0; i < tries; ++i)
		{
			if (std::find(std::begin(myArray), std::end(myArray), myArray[i]) != std::end(myArray))
			{
				std::cout << "the number is already entered , please guess again: " << std::endl;

				std::cin >> guess;

				myArray[tries++] = guess;
			}
		}*/
		

		while (check != true)
		{
			if (guess > max || guess < min || !std::cin)
			{

				std::cout << "\nsorry " << playerName << " your guess is either outside the range, invalid or not a number!" << std::endl;

				if (!std::cin)
				{
					std::cin.clear();
					std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
					std::cout << "please enter an Integer between " << min << " and " << max << std::endl;
					std::cin >> guess;
				}

				continue;
			}
			for (int i = 0; i < myArray [99]; i++)
			{
				if (guess==(myArray[i]))
				{
					std::cout << "the number is already entered , please guess again: " << std::endl;

					std::cin >> guess;

					myArray[tries++] = guess;
				}
				
			}
			if (guess > number)
			{

				std::cout << "\nThe number guessed is too high, Please enter your guess again:" << std::endl;

				std::cin >> guess;

				myArray[tries++] = guess;

			}

	    

			else if (guess < number)

			{
				std::cout << "\nThe number guessed is too low, Please enter your guess again:" << std::endl;

				std::cin >> guess;
				
				myArray[tries++] = guess;

			}

			
			else if (guess == number)
			{
				std::cout << "\nYour guess is correct! congratulation " << playerName << " you got it in " << tries << " guesses" << std::endl;

				std::cout << "you have guessed : " << std::endl;

				for ( i = 0; i < tries; ++i)
				{
                  std::cout << myArray[i] << std::endl;
				}
				check = true;

				std::cout << "\nwould you like to play again?" << std::endl;

				std::cout << "type Y to play again or press any key to exit : " << std::endl;

				std::cin >> response;

				std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

				std::cin.clear();

			}
		}
	} while (response == 'Y' || response == 'y');

	system("pause");

}
I simplified your program a bit:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <algorithm>



int main()
{
    char response;

	int guess;

	int number;

	int tries = 0;

	const int min = 0;

	const int max = 100;

	int myArray[99] = {};

	bool check = false;

	int i;

	std::string playerName;

	srand(time(0));
	number = rand() % 101;

	std::cout << "Welcome to The Guessing game\ninput your name please: " << std::endl;

	std::getline(std::cin, playerName);

	std::cout << "\nwelcome " << playerName << "!" << std::endl;

	while (check != true)
	{
		std::cout << "Please enter a number between 0 and 100 please:  \n" << std::endl;

		if (std::cin >> guess)
		{
			myArray[tries++] = guess;
			if (std::find(myArray, myArray + tries - 1, guess) != (myArray + tries - 1))
				std::cout << "the number is already entered" << std::endl;
			else if (guess > number)
				std::cout << "\nThe number guessed is too high" << std::endl;
			else if (guess < number)
				std::cout << "\nThe number guessed is too low" << std::endl;
			else
			{
				std::cout << "\nYour guess is correct! congratulation " << playerName << " you got it in " << tries << " guesses" << std::endl;

				std::cout << "you have guessed : " << std::endl;

				for ( i = 0; i < tries; ++i)
				{
					std::cout << myArray[i] << std::endl;
				}
				tries = 0;

				std::cout << "\nwould you like to play again?" << std::endl;

				std::cout << "type Y to play again or press any key to exit : " << std::endl;

				std::cin >> response;

				std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

				std::cin.clear();

				check = ! (response == 'Y' || response == 'y');
			}
		}
		else
		{

			std::cout << "\nsorry " << playerName << " your guess is either outside the range, invalid or not a number!" << std::endl;
			std::cin.clear();
			std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
		}
	}

	system("pause");

}
@coder777, your program works but will not re-run
To enable re-run, after line 75, add
1
2
3
4
5
6
 // reset stuff and get new number
   if(!check) { 
         number  = rand() % 101; // guess new number
         tries = 0; // reset tries
         std::fill(myArray, myArray+99, 0); // reset myArray
       }
@blongho
It will rerun. Just another number is not generated.
See line 63. fill(..) is not necessary.
Hello MJnoob,

oh yes, I thought you meant I have to make a header for that method


I did say function not another file. Also I think you are confusing what a "header file" is for and a ".cpp" file is.

Header files are things like "<iostream>", notice the "<>"s these are the header files that come with the compiler and are required by the program.

Header files that you write will have a ".hpp" or ".h" after the file name. And usually contain prototypes, but not code, usually.

the part where you said :
but I would remove the "std::cin >> guess;" as this is the wrong places to use it.

isn't this the only way for me to make sure I am saving the guesses using the next line?

No. If you leave the "cin"s where they are you would have to check the entry after each, hence the function rather than duplicating code.

When you compile a C++ program it will compile from the first line followed by the next line. When you run the program it will start at the first line after the opening { of "main" and move to the next line. Loops will repeat until they fail and then it is to the line right after the loop. If you keep this in mind when you write a program it will help you understand the program flow.

I have not put your revised code through a compiler yet, but at first glance I do see some improvement.

coder777 has a good example to shorten your program. Even if you do not understand all of his code do look at it for how the program flows and where things are done.

This is what I did to rearrange what you started with. I did not attempt to rewrity what you had just make it work. The important part here is how the program flows and what is done where.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
//#include <algorithm>  // <--- Not needed.
#include <limits>


int main()
{
	constexpr size_t MAXSIZE{ 15 };  // <--- Added.
	const int MIN{};  // <--- Changed. "min" shuld be all caps.
	const int MAX{ 100 };  // <--- Changed. "max" shuld be all caps.

	char response{};
	std::string playerName;
	bool firstTime{ true };  // <--- Added.

	//srand(unsigned int(time(0)));
	srand(static_cast<size_t>(time(NULL)));  // <---  Moved. "srand" should be here. Only needs done once.

	std::cout << "Welcome to The Guessing game\ninput your name please: ";  // <---  Moved. here. Only needs done once.

	std::getline(std::cin, playerName);

	do
	{
		int guess{};
		int number{};
		int tries{};
		int myArray[MAXSIZE]{};  // <--- Array should be 15 or maybe 20. Anything else is wasted memory.
		bool check = false;  // <--- Added.

		number = rand() % 101;
		//number = 24;  // <--- Used for testing.

		if (firstTime)  // <--- Added.
			std::cout << "\nwelcome " << playerName << "!\n" << std::endl;
		else
			std::cout << "\nWelcome back " << playerName << "! Let's play a game.\n" << std::endl;

		firstTime = false;

		std::cout << "Please enter a number between 0 and 100 please: ";

		while (!check)
		{
			std::cin >> guess;  // <--- "cin" done here for following checks.

                    // ******************* Code for checking entry ************************

			if (guess > MAX || guess < MIN || !std::cin)
			{

				std::cout << "\nsorry " << playerName << " your guess is outside the range or invalid,\nplease enter an integer between " << MIN << " and " << MAX << ": ";
				if (!std::cin)  // <--- Done this way because of first if statement. This could be done before the first if statement.
				{
					std::cin.clear();
					std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
				}

				continue;
			}

			// <--- Once you have a good number this checks if previously entered.
			for (int lc = 0; lc < tries; lc++)
			{
				if (guess == myArray[lc])
				{
					std::cout << "\n That number has already been guessed." << std::endl;
					tries--;
					continue;
				}
			}
                    // ********************************************************************

			if (guess > number)
			{

				std::cout << "\nThe number guessed is too high, Please enter your guess again: ";

				//std::cin >> guess;  // <--- If you do the "cin" here you would need to follow with the above code to check the number entered.

				myArray[tries++] = guess;
			}

			else if (guess < number)

			{
				std::cout << "\nThe number guessed is too low, Please enter your guess again: ";

				myArray[tries++] = guess;
			}


			else if (guess == number)
			{
				myArray[tries++] = guess;

				std::cout << "\nYour guess is correct! congratulation " << playerName << " you got it in " << tries << " guesses" << std::endl;

				std::cout << "you have guessed : " << std::endl;

				for (int i = 0; i < tries; ++i)
				{
					std::cout << myArray[i] << std::endl;
				}

				//std::cout << number << std::endl;

				check = true;

				std::cout << "\nwould you like to play again?" << std::endl;

				std::cout << "type Y to play again or press any key to exit: ";

				std::cin >> response;

				std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

				std::cin.clear();
			}
		}

		system("cls");  // <--- Added.
	} while (response == 'Y' || response == 'y');
	  // <--- If you change "algorithm" to "cctype" you could write the while condition as:
	  //  while(std::toupper(responce) == 'Y').

	system("pause");

}

Any questions let me know.

Hope that helps,

Andy
Topic archived. No new replies allowed.