Connecting Tech Pros Worldwide Forums | Help | Site Map

What is an alternative to a goto statement?

Newbie
 
Join Date: Oct 2009
Posts: 4
#1: 10 Hours Ago
Expand|Select|Wrap|Line Numbers
  1. #include <iostream> 
  2. #include <cstdlib> 
  3. #include <time.h> 
  4. #include <string>
  5. #include <algorithm>
  6.  
  7. using namespace std; 
  8.  
  9. int dieRoll(); 
  10.  
  11. int main(int argc, char* argv) 
  12.  
  13.     int looper = 0;
  14.     int arrRolls[6]; 
  15.     int roll; 
  16.     string again = ""; 
  17.     srand((unsigned)time(0));
  18.  
  19.     do{
  20.  
  21.     for (int k = 0; k < 6; k++) 
  22.     { 
  23.         arrRolls[k] = 0; 
  24.     } 
  25.  
  26.     for (int i = 1; i <= 100; i++) 
  27.     { 
  28.         roll = dieRoll(); 
  29.         cout << "Die Roll " << i << ": " << roll << endl; 
  30.         arrRolls[roll - 1]++; 
  31.     } 
  32.  
  33.     for (int j = 0; j < 6; j++) 
  34.     { 
  35.         cout <<  j + 1 << " : " << arrRolls[j] << " times." << endl; 
  36.     } 
  37.     start:
  38.     cout << "Would you like to roll the dice again(Yes or No)?:" << endl; 
  39.     cin >> again;
  40.     transform(again.begin(), again.end(), again.begin(), tolower);
  41.     } while (again == "yes");
  42.     if (again != "no" && again != "yes"){
  43.     cout << "Please enter yes or no." << endl; 
  44.     goto start;
  45.  
  46.     }
  47.     return 0;
  48. }
  49.  
  50. int dieRoll()
  51. {
  52.     int result;
  53.     result = (rand() % 6) + 1;
  54.     return result;
  55. }

Newbie
 
Join Date: Oct 2009
Posts: 4
#2: 10 Hours Ago

re: What is an alternative to a goto statement?


oh and this is for C++
Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,171
#3: 9 Hours Ago

re: What is an alternative to a goto statement?


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.
Reply