What is an alternative to a goto statement?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • wutang
    New Member
    • Oct 2009
    • 5

    What is an alternative to a goto statement?

    Code:
    #include <iostream> 
    #include <cstdlib> 
    #include <time.h> 
    #include <string>
    #include <algorithm>
    
    using namespace std; 
    
    int dieRoll(); 
      
    int main(int argc, char* argv) 
    
    { 
    	int looper = 0;
        int arrRolls[6]; 
        int roll; 
    	string again = ""; 
    	srand((unsigned)time(0));
    
    	do{
    
    	for (int k = 0; k < 6; k++) 
        { 
            arrRolls[k] = 0; 
        } 
      
        for (int i = 1; i <= 100; i++) 
        { 
            roll = dieRoll(); 
            cout << "Die Roll " << i << ": " << roll << endl; 
            arrRolls[roll - 1]++; 
        } 
      
        for (int j = 0; j < 6; j++) 
        { 
    		cout <<  j + 1 << " : " << arrRolls[j] << " times." << endl; 
        } 
    	start:
    	cout << "Would you like to roll the dice again(Yes or No)?:" << endl; 
        cin >> again;
    	transform(again.begin(), again.end(), again.begin(), tolower);
    	} while (again == "yes");
    	if (again != "no" && again != "yes"){
    	cout << "Please enter yes or no." << endl; 
    	goto start;
    
    	}
    	return 0;
    }
    
    int dieRoll()
    {
    	int result;
    	result = (rand() % 6) + 1;
    	return result;
    }
  • wutang
    New Member
    • Oct 2009
    • 5

    #2
    oh and this is for C++

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      A loop of some sort, for, do while, while.

      Your current problem is any such loop would intersect with your main loop but by moving lines 43 and 44 and inserting just after line 41 you could then easily have a nested loop doing the job.


      BTW when posting code please use [code] ... [/code] tags. Please don't just post code post a description of your problem including any relevant behaviour (expected behaviour, actual behaviour) and input and output data.

      Comment

      • wutang
        New Member
        • Oct 2009
        • 5

        #4
        ahh ok got it. Thanks!
        I see that I also need to move the while statement in line 42 to just b4 line 48 the return 0 in order to work.

        Comment

        Working...