Hello, thank you for taking the time to read this.
I am very (very very) new at c++, and I've always heard bad things about the goto function. I have constructed a program in which the easiest (and apparently most efficient) way to make it work properly is with the goto function.
Should I try around with for and while loops until I can get the same result, or just leave the goto in there? Do the drawbacks outweigh the benefit of extremely easy to write / read (I think) code?
Here's where it's implemented in the code.
This should get a name from the user, then generate stats for the character named. Then the user has a choice to re-roll the stats, or accept them. If the user chooses to re-roll, it sends you back to the reroll: label. I worked around with while statements for a bit, and even stumbled across an infinite loop, which was when I decided to use goto instead.
int main(int argc, char *argv[])
{
character player;
cout<< endl << "Please enter your desired name. ";
getline(cin,player.name);
cout << endl;
reroll: //Go here if the user wants to re-roll the stats.
char input = 'x';
player = CharGen(player);
PrintCharSheet(player);
reask: //Label to go to if the user inputs an invalid char
cout << "Re-roll stats? (y/n): ";
cin >> input;
cout << endl;
if (input == 'y')
{
goto reroll;
}
if (input == 'n')
{
cout << endl << "Welcome, to the wonderful world of nothing." << endl;
}
if (input != 'y' && input != 'n')
{
cout << endl << "Please enter valid input.\n";
goto reask; // The goto function... properly used?
}
system("PAUSE");
return EXIT_SUCCESS;
}
Is this a good place to use goto?
Thank you for your time, any comments and/or suggestions are gladly accepted.
There are no good uses of goto. :P
Probably the only one that might be considered a good use of goto is breaking out of nested loops, but this is only due to the fact that C++ lacks labelled break. Additionally, breaking out of loops is also a bad practice, not as bad as using goto, but better use it sparingly... :D
Never EVER use goto in C++ code, it was only left in C++ because of portability with older C code. Use firedraco's approach (except that he made a slight mistake):
1 2 3 4 5 6 7
while(input != 'n' && input != 'y') {
cout<<"re-roll...";
//etc
if(input != 'y' && input != 'n')
cout<<"input something valid";
}
//welcome to the world
However; when I try to implement either of those two snippets of code, I find that when entering an invalid character, it outputs what it's supposed to, but then goes ahead and re-rolls anyway, instead of asking again.
I will work on this some more, thank you all, once again for your input.
And Grey Wolf, I'll read that article and see if I can learn something from it. Thanks. :)
EDIT: Got it working without using goto. Thanks, guys!