Hi again,
Looking for some feedback on my code.
Please can someone tell me how to stop infinite loop errors.
If the user types in a string or a char instead of an int.
If the user types in an int instead of a string or char.
How can I stop an infinite loop from occurring in these situations?
I want the program to output a message like:
"Please enter a whole number"
or
"Please enter a Y or N"
Thanks so much!
Code:
#include "stdafx.h"
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <string>
using namespace std;
int randRange(int low, int high)
{
return rand() % (high - low + 1) + low;
// rand() gives us an initial random number
// we want the total number of values in our range (between 1 and our max value) so we add '1'
// we add 'low' (lowest possible value) to bring our range up from 0
}
int playgame()
{
cout << "Pick a number between 1 and 100: ";
int chosen = randRange(1, 100);
int number = 0;
for (int attempts = 10; ; attempts--)
{
cin >> number;
if (number < 1 || number > 100)
{
cout << "Please make sure to pick your number from between the values 1 and 100\n\n";
}
else if (number < chosen)
{
cout << "The number is higher, guess again!\n\n";
}
else if (number > chosen)
{
cout << "The number is lower, guess again!\n\n";
}
else if (number == chosen)
{
cout << "You guessed the correct number!\n\nThe number was: " << chosen << "!!\n\n";
cout << "Do you wish to play again? Y/N: ";
string input;
cin >> input;
if (input == "y" || input == "Y")
{
cout << "\n\n";
playgame();
}
else
{
return 0;
}
}
}
}
int main()
{
srand(time(NULL));
playgame();
return 0;
}