return to the beginning of a do-while loop after exiting It.

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 ?
Last edited on
Recursion is not the solution you want.

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(...);
Last edited on
Would using a function with recursion be a possible solution ?


That's one possible solution, but frankly the loop sounds poorly designed. Normally the error handling goes inside the loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#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" ;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#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 );
}
Last edited on
Thank you all. It's clear now
Topic archived. No new replies allowed.