How to end a loop early if a user says to C++ - c++

Note: This is a homework assignment.
I am trying to make a program that plays the game Pig! Pig is a game with the following rules:
1. First to get 100 GAME POINTS is the victor.
2. On your turn, you roll a dice. If you get a 1 at any roll, you end your turn and add 0 to your GAME SCORE.
3. If you roll any value other than a 1, you have the option to HOLD or PLAY. If you PLAY, your roll is added to your TURN SCORE and you roll again. If you HOLD, your TURN SCORE is added to your GAME SCORE and the turn passes to the computer.
The game is coming along very easily until I get to the following problem (see code):
int player(){
char PlayAgain = 'Y';
int turn_score = 0;
while (PlayAgain != 'N' || PlayAgain != 'n'){
int dice;
srand(time(NULL));
dice = rand() % 6 + 1;
turn_score = turn_score + dice;
if (dice != 1){
cout << "You rolled a " << dice << "! Would you like to roll again? [Y/N]: ";
cin >> PlayAgain;
if (PlayAgain == 'N' || PlayAgain == 'n'){
/*END TURN AND return turn_score;*/
}
}
if (dice == 1){
cout << endl << "Oops! You rolled a 1! Your turn is ended, and you add nothing to your score.\n";
system("PAUSE");
/*END TURN, NO SCORE ADDED*/
}
}
}
How can I have the program end the loop prematurely (if either the play HOLDS or dice == 1) and return the proper value (if HOLD, return turn_score. Else return 0)? [See two noted sections]

You can use break to get out of a loop. Since you're saying that you want to return "the right value" then you should do something like that:
On the first if clause
if (PlayAgain == 'N' || PlayAgain == 'n'){
/**Game-Specific logic here**/
return turn_score
}
and on the second one:
if (dice == 1){
cout << endl << "Oops! You rolled a 1! Your turn is ended, and you add nothing to your score.\n";
/**Game-Specific logic here**/
cin.get();
return turn_score;
}
A return statement doesn't need to be at the end of the function and more than one return statements can co-exist inside the same function

Rather then correcting your code I would like to make you clear about what actually is needed here.
Ever heard of break; statement.Let us understand with a simple example
see the following code snippet where your program is taking input from the user,it keeps on taking input from the user until you press 'A'
char var;
while(true)
{
cin>>var;
if(var=='A') break;
}
Now in this program,the while loop is set to true and will keep on running and taking input from the user,and the if statement will not run until the user have entered 'A'. AND the moment 'A' is given as the input,break will take the control out of the while loop for you.

How about having your 'return' statement (with the proper value depending on the case) inside your loop? This will break both the loop and the function, but returning the value you needed.

Related

Running a simple C++ function

I've just started learning the basics in C++ and currently am trying to make a program that does a few basic things. The problem I have is occurring in the pasted function below.
At this point it literally does nothing when it runs. All I'm trying to do it make it so the function runs over and over again forever, until the user enters the letter 'q'.
The function must keep running even if the user enters some random string, anything, 'q' is the only keystroke that should stop the loop.
I have tried toying around with 'cin.whatever" and haven't found success. If you have an answer please provide as much explanation as possible. Thank you!
void menu()
{
cin.clear();
cin.ignore();
char quit = 'w';
while (quit != 'q') // while loop to allow the user infinite tries
{
cout << "Which story would you like to play? Enter the number of the story (1, 2, or 3) or type q to quit: " << endl;
cin >> quit;
if (quit < '1' or quit > '3') // make sure the user picks a valid choice
{
cout << "Valid choice not selected." << endl;
}
if (quit == '1')
{
story1(); // run story 1
}
if (quit == '2')
{
story2(); // run story 2
}
if (quit == '3')
{
story3(); // run story 3
}
if (quit == 'q')
{
cout << "good bye" << endl;
break;
}
}
}
Try adding single quotes around your 1,2,3 like you did with the q. The cin is expecting a char to be entered so evaluate it as such. e.g: if (quit == '1')

how to get a specific character from input?

i done a tutorial about getchar:
getChar - c++ tutorial
this all worked till i wanted to make some modifications.
char c;
puts("enter . to exit");
do{
c=getchar();
} while (c != '.'); {
if(c == 's'){
upgradeOne();
cout << "upgrade1 is done" << endl;
}
if (c == 'a'){
upgradeTwo();
cout << "upgrade2 is done" << endl;
}
}
while (total < 999){
total += i;
cout << total << endl;
}
i want to use specific methods when the user input equels an specific character.
if the user types a the method upgradetwo() must be activated.
how am i supposed to do this?
The repetitive processing of your input takes place in the do...while loop. The loop is left only when '.' is pressed.
If you want to react on specific chars, you have to move your if(c==...) statements into this loop (i.e. Between the getchar() and the while).
If you want to run the loop until the user enters period(.), then you can use some bool flag which will be set to true initially. Then write a while which will run until the flag is false. In the while read the character and if it is a period then set the flag to false.
or you can run the while loop infinitely and break the loop if the char is a period else continue.

making a line run once, Text based game

I am doing a text based game in class for beginner coders, and I need some quick help.
case 1:
cout << "\n You are in a underground room you, look around there is no way back up to the hole you fell through. \n";
cin >> input;
if ( input == 'l'){
cout << "\n You turn left and see a dull lanturn.\n";
cin>>input;
if ( input == 'g')
cout << "\n You grab the dull lanturn\n";
cin>>input;
if ( input == 'u')
cout << "\n You turn the lanturn on, it casts a bright light. \n";
}
if ( input == 'r')
cout << "\n You turn right, and see nothing of interest.\n";
else if (input == 'n')
room = 2;
else
cout<<"input not recognized"<<endl;
break;
I only want this line to run one time
if ( input == 'l'){
cout << "\n You turn left and see a dull lanturn.\n";
cin>>input;
if ( input == 'g')
cout << "\n You grab the dull lanturn\n";
cin>>input;
if ( input == 'u')
cout << "\n You turn the lanturn on, it casts a bright light. \n";
}
How do I go about doing this.
Guessing from your break statement, and the strings, you are in a loop that keeps asking for input and then does something depending on the input.
Knowing this, you should begin by figuring out when you want this line to run and develop a strategy from there.
E.g. if you decide that the first time someone presses 'l' you wish to execute the if statement, than you need to keep a reminder of whether you already went through there and test that in your condition.
If you decide that it can only happen when you are in a certain room and do not have a (lit?) lantern in your inventory, then your check becomes more complicated, because it needs to test more conditions, but still works along the same basic principle.
Finally, you may be missing an else before the if(input == 'r'), leading to the possibility that the user types "lr", which would execute two ifs in one iteration of your loop.

while statement is unable to read the correct char input

hi i am new to c++ and i dont understand why my while statement doesnt work now. it was working when i tried to do it earlier.
Full code is available at: http://pastebin.com/aeH5fKwh
basically here is the while loop (i excluded all the unnecessary parts, i left the inside of the while loop intact for viewing purpose)
int main()
{
unsigned int seed;
char input;
bool done;
for (int round = 0; round < 5; round++)
{
done = false;
cout << "\nEnter seed: ";
cin >> seed;
cout << "\nRound 1" << endl;
while(!done)
{
cout << "\nDo you wish to draw another card [y][n]: ";
cin >> input;
while (input != 'y' && input != 'n')
{
cout << "Invalid input! Please enter [y][n]!" << endl;
cin >> input;
}
if (input == 'y')
{
dealExtra(playerHand, deck, gameInfo);
cout << "Your cards are ";
printHand(playerHand, gameInfo.playerCardCount);
}
else
done = true;
}
}
cout << endl;
return 0;
}
when i try entering anything that is not 'y', 'n', it will tell me that my input is invalid. But when i try to enter 'y' or 'n', it kinda just ignored it and nothing else happened.. i checked with cout statement and found that it manage to get into the if (input == 'y') statement, but it doesnt seem like it is doing anything else. Everything was fine till 20 minutes ago and i really couldnt figure out whats wrong.
Edit: i ran another test using "cout << '[' << input << ']' << endl;".. it seems like the program is able to get my first input, but then it just hangs there afterwards.. what i get is something like:
Do you wish to draw another card [y][n]: y
[y]
y
y
y
y
I compiled this on linux terminal using g++
if extra codes is needed, i'll edit and add them.. thanks!
When you ask for input from the console, most implementations buffer characters until a newline key is pressed.
After the newline is received, the first character of the buffer is returned. The newline still remains in the buffer as well as any extra characters.
In your case, the second cin >> input statement will read the newline from the buffer.
As an experiment, try entering "frog" and single step through your program. This should illustrate the case of residual characters in the buffer.
Try cin.ignore(1000, '\n') after the first cin >> input. The ignore method will eat up any remaining characters in the buffer until the newline is found.
Make below statements inactive
dealExtra(playerHand, deck, gameInfo);
printHand(playerHand, gameInfo.playerCardCount);
and check if it works, then try making one of the above statements active alternately to find out in which function the flow is getting lost. And so on.
If you feel lazy to run a debugger, and plan to use cout<< statements to find a hanging call, you should flush you cout:
( cout << "I am here and going to hang" ).flush() ;
Otherwise you can't see recent output just because it's still in the output buffer. Try this and you well might see what call hangs your program.
You have an infinite loop inside checkComputerHand:
bool done = false;
while(!done)
{
if(sum == 11 && checkAce == true)
{
computerHand[aceLocation].value = 11;
done = true;
}
if(sum > 11 && checkAce == true)
{
computerHand[aceLocation].value = 1;
done = true;
}
// What if checkAce wasn't true? Infinite loop!
}
Also, the first two lines of newGame do not make any sense:
void newGame(Card playerHand[], Card computerHand[], Statistics &gameInfo)
{
playerHand = '\0';
computerHand = '\0';
// ...
}
Array parameters are silently rewritten by the compiler as pointer parameters. So all you're doing is assigning the null pointer to those local pointers. Probably not what you intended...

C++ "while" explanation

i am not very sure the while(choice == 1 || choice ==2);
can anyone explain. i understand this
if(choice ==1)
displayMonthly(rainfall);
else if(choice == 2)
displayTotal(rainfall);
i just don't understand the code after this. can anyone explain to me please.
int main()
{
//declare variable and array
int choice = 0;
double rainfall[12] = {0.0};
//get rainfall amounts
for(int x =0;x<12;x++)
{
cout << "Enter rainfall for month "<< x+1<< ": ";
cin >> rainfall[x];
}
do
{
//display menu and get menu choice
cout <<endl;
cout << "1 Display monthly amounts" << endl;
cout << "2 Display total amount" << endl;
cout << "3 End program" << endl;
cout << "Enter your choice : ";
cin >> choice;
//call appropriate function or end program
if(choice ==1)
displayMonthly(rainfall);
else if(choice == 2)
displayTotal(rainfall);
}while (choice == 1 || choice ==2);
return 0;
}
It's telling you to keep looping as long as the choice is 1 or 2, but it's entirely separate from the if statement.
Could also be coded as
while(true) {
cout stuff...
if(choice==1)
...
else if(choice==2)
...
else
break;
}
Which may be a little more readable but some old schoolers will freak right out if they see while(true)--that used to be drummed into people as a big red flag indicating a potential bug (Apparently by anyone completely unable to analyze code since the functionality is no different).
This is a do ... while loop. The idea is that the code within the block will continue executing as long as the condition (choice == 1 || choice ==2) is true.
Here is more information from a cplusplus.com article on Control Structures:
do statement while (condition);
Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. For example, the following example program echoes any number you enter until you enter 0.
The do-while loop is usually used when the condition that has to determine the end of the loop is determined within the loop statement itself, like in the previous case, where the user input within the block is what is used to determine if the loop has to end. In fact if you never enter the value 0 in the previous example you can be prompted for more numbers forever.
You can also think of is this way. You might use a do-while structure if you always want the code within the block to be executed at least once. This is exactly the case in your program since you always want to display the prompt, and can only decide whether the loop will continue after you receive and process the user's input.
In this app, if the user hits 1 or 2, it means that they wanted to see either monthly or total rainfall. What this implies is that they haven't requested to 'End program'. The code assumes that if the user has chosen 1 or 2 that they should continue using the application. If they have chosen ANYTHING else, (eg. 3, just like the menu says) then the condition choice == 1 || choice == 2 will evaluate to false and the loop with terminate, resulting in the application closing.
Basically what the do ... while loop here does is keeps repeating its self as long as the choice is 1 or 2.
After the 'do', the user is prompted to enter their choice, 1 2 or 3. If they choose 1 or 2, their respective function is called. Then the loop repeats. If they choose 3, the loop does not repeat so the program ends.
Hope this helped!