Using a switch in a do..while loop, in C++

1.8k views Asked by At

A simple programm that reads strings, and responds using a switch;

in this do-while loop containing a switch, I am able to run case 1-4 with no issues, but once i hit the default case, the programme simply loops the default case over and over again the code is as follows;

    do {    switch ( switchstring (entry, input) )
/*the switchstring function is one 1 wrote to convert a given entry(string), 
into an input(integer)*/   
    {
    case 1:
        //code
        repeat = 2;
        break;
    case 2:
        //code
        repeat = 2;
        break;
    case 3:
        //code
        repeat = 2;
        break;
    case 4:
        //code
        repeat = 2;
        break;
    default:
        //code
        repeat = 1;
        break;}} while(repeat == 1);

the 2nd question is regarding my switchstring() function; is there a way to change the switch function such that it reads;

    case (insert string):

i.e. so that I can remove the entire switchstring() function

thanks in advance!

2

There are 2 answers

4
mazhar islam On

Show us how switchstring (entry, input) works.

The problem you are facing is because, in default you do the following:

repeat = 1;

Which makes while(repeat == 1) always true. And then switchstring (entry, input) always return something that makes your switch block always go the the default case again.

2
Puneet Chawla On
  1. When no case will be true in switch, then it will go in default case of switch and you are specifying repeat=1; in default. After that while condition will be checked and it will be true because repeat is 1, again it will go to do and check condition, your switch function will return something and it will go to default.

  2. To solve 2nd question regarding your switchstring() function, you have to show your code what you are doing in that function, So that i can give you best suggestion.