Sorry, I forgot to write my question again in the top.
I couldn't find a way to make the program identify when a number is entered twice in a row.
Please help...
Use a std::set<int> to hold the numbers which were already entered, and check if the new number which was entered is present in the set. Something like this:
#include <iostream>
#include <set> // http://en.cppreference.com/w/cpp/container/setint get_unique_number( int minv, int maxv, int exit_value, const std::set<int>& numbers_already_entered )
{
// http://en.cppreference.com/w/cpp/container/set/emptyif( !numbers_already_entered.empty() ) // if some numbers were already entered
{
// display those numbers
std::cout << "these numbers have been already entered: [ " ;
// http://www.stroustrup.com/C++11FAQ.html#forfor( int n : numbers_already_entered ) std::cout << n << ' ' ;
std::cout << "]\n" ;
}
std::cout << "enter a number between " << minv << " and " << maxv
<< " ( " << exit_value << " to give up): " ;
int number ;
if( std::cin >> number ) // if the user entered an integer
{
if( number == exit_value ) return number ; // if the user entered exit_value return it
// otherwise, check for out of range number
elseif( number < minv ) std::cout << number << " is too small\n" ;
elseif( number > maxv ) std::cout << number << " is too big\n" ;
// otherwise check if this number was already entered earlier
// http://en.cppreference.com/w/cpp/container/set/findelseif( numbers_already_entered.find(number) != numbers_already_entered.end() )
std::cout << number << " was already entered earlier\n" ;elsereturn number ; // ok, entered value is unique and within range, return it
}
else // bad non-integer input
{
std::cout << "that is not a number\n" ;
// http://en.cppreference.com/w/cpp/io/basic_ios/clear
std::cin.clear() ; // clear the failed state of the input stream
// http://en.cppreference.com/w/cpp/io/basic_istream/ignore
std::cin.ignore( 1000, '\n' ) ; // throw away the bad input
}
return get_unique_number( minv, maxv, exit_value, numbers_already_entered ) ;
}
int main() // simple test driver
{
constint MIN_NUMBER = 1;
constint MAX_NUMBER = 100;
constint EXIT_VALUE = -1;
std::set<int> numbers_already_entered ;
int number ;
// loop till exit_value is entered
while( ( number = get_unique_number( MIN_NUMBER, MAX_NUMBER, EXIT_VALUE, numbers_already_entered ) ) != -1 )
{
// add this number to the set of already entered numbers
// http://en.cppreference.com/w/cpp/container/set/insert
numbers_already_entered.insert(number) ;
std::cout << "you entered " << number << '\n' ;
}
}