Write your question here.
Hi.
I'd like to know how I could return to the beginning of a do-while loop after I've exited It without using the goto statement or a switch. Let's say I ask the user to input a number between 1 and 10 and the do-while loop exits when he enters anything below 1 or above 10.I'd like to print a message saying "I said between 1 and 10 DUMBASS!!" or "between 1 and 10 please sir/madam" and then return to the loop.
Would using a function with recursion be a possible solution ?
Generally if you want to repeat (loop) something, you put it in a loop. If what you want to loop is a do/while loop, that just means you put it in another loop:
1 2 3 4 5 6 7 8
do
{
do
{
// get input from user
}while(...);
}while(...);
#include <iostream>
#include <limits>
#include <string>
#include <sstream>
int getNumBetween( int min, int max )
{
std::ostringstream os ;
os << "Enter a number between " << min << " and " << max << ": " ;
const std::string prompt = os.str() ;
os.str("") ;
os << "I said between " << min << " and " << max << " DUMBASS!!\n" ;
const std::string error = os.str() ;
int num ;
while ( std::cout << prompt && (!(std::cin >> num) || num < 1 || num > 10) )
{
std::cout << error ;
std::cin.clear() ;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n' ) ;
}
return num ;
}
int main()
{
int num = getNumBetween(1,10) ;
std::cout << "You chose " << num << ".\n" ;
}
#include <iostream>
int main()
{
int n;
do
{
std::cout << "Enter a number berween 1 and 10 inclusively: ";
std::cin >> n;
if ( n < 1 || n > 10 )
{
std::cout << "I said between 1 and 10 DUMBASS!!" << std::endl << std::endl;
}
} while ( n < 1 || n > 10 );
}