I'm a self taught developer trying to learn c++, I found this exercise on google and I wrote the code for it, though all my conditions were correct, it wouldn't work, when I checked their answer, I found this line of code- if (!(cin >> guess)). I honestly don't see the relevance, I don't know why it made my loop not to work. Here is my code:
int main(int argc, char* argv[])
{
int nUserRandNum = 0;
int randomNumber=0;
srand (time(NULL));
randomNumber = rand() % 100 + 1;
printf("Please enter a random number between 1 - 99 \n");
scanf("%d", &nUserRandNum);
do
{
if (randomNumber < nUserRandNum)
{
printf("Try to go a little higher than \n", nUserRandNum);
}
else
{
printf("You might want to go a little lower than \n", nUserRandNum);
}
}
while (randomNumber != nUserRandNum);
printf("You got it!!!");
system("Pause");
return 0;
}
When I checked the answer they had:
int random_number, guess;
// Initialize random seed.
srand (time(NULL));
// Generate random number between 1 and 100
random_number = rand() % 100 + 1;
cout << "Guess our number (1 to 100) ";
cin>>guess;
do
{
if (!(cin >> guess))
{
cout << "Please enter only numbers" << endl;
}
else
{
if (random_number < guess)
cout << "The secret number is lower than " << guess << endl;
else if (random_number > guess)
cout << "The secret number is higher than " << guess << endl;
}
} while (random_number != guess);
cout << "Congratulations!" << endl;
what does that if statement do {if (!(cin >> guess)) }
? And are there other reasons my loop didn't work?