Hi, I have this "number game" which i just learned tonight ..It runs..but ,not without this warning box poping up, which says: "uninitialized local variable 'guess' used"...This confusing me because i know i did everything exactly like i was taught ...can you find/fix my problem abd explain please it'll be a blessing ...thankyou so much..

#include <iostream>
#include <ctime>
using namespace std;

int main()
{
	int random;
	int guess;

	srand(static_cast<unsigned int>(time(0)));
	random = rand()%7+1;

	std::cout << "Guess my number! (1-7)\n";

	while (guess != random)
	{
		std::cin >> guess;
		std::cin.ignore();
	if (guess < random)
	{
		std::cout << "Too Low!!!\n";
	}
	if (guess > random)
	{
		std::cout << "Too High!!!\n";
	}
	if (guess == random)
	{
		std::cout << "You Won!!! My number was: "<< random << "\n";
		std::cin.get();
	}
	}
}

The reason is that you have used 'guess' ( while (guess != random) ) without giving it a value first. i.e. the first time you try to compare 'guess' to 'random', guess has no value. So initialise it to 0.

No need to do that for 'random' as you initialise it before using it anyway.

Though you could remove the line: int random; and replace the line: random = rand()%7+1; with: int random = rand()%7+1; if you wanted to.

an alternative to the explicit initiation, is you could change your while loop to a do-while:

#include <iostream>
#include <ctime>
using namespace std;
       
 int main()
{
      int random;
      int guess;
       
      srand(static_cast<unsigned int>(time(0)));
      random = rand()%7+1;
       
      std::cout << "Guess my number! (1-7)\n";
       
      do
      {
            std::cin >> guess;
            std::cin.ignore();
            if (guess < random)
            {
                  std::cout << "Too Low!!!\n";
            }
            if (guess > random)
            {
                  std::cout << "Too High!!!\n";
            }
            if (guess == random)
            {
                  std::cout << "You Won!!! My number was: "<< random << "\n";
                  std::cin.get();
            }
      }
      while (guess != random);
}

just an alternative if you were curious

~J

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.