I've created a program that asks for shoe size. If the shoe size is correct, the user will get a message that says, "You are correct would you like to try again?" They can either answer yes or no. If they select "no" the program will break and they will get another message that says, "Thanks for playing!"
Is there a way to basically force the program to break back into the while loop if the user enters yes as an answer instead of no?
#include <iostream>
#include <string>
using namespace std;
int main()
{
int shoesize = 13;
int input;
string answer;
while (input != shoesize) {
cout << "Guess my shoe size!";
cin >> input;
if (input == shoesize) {
cout << "You are correct! Thanks for Playing! Would you like to play again? \n";
cin >> answer;
if (answer == "no") {
cout << "Thank you for playing!";
}
}
}
return 0;
}
Easily the best way to write something that "repeats continuously until you want to quit" is to just do something like this:
while(true) {
.. do something ..
.. ask "do you want to quit" ..
if (answer == "yes") {
break;
}
}
Programmers will instantly recognize the while(true){} "endless" loop, and look for the break statement which – as the name implies, "breaks out of" the innermost loop, ending the "endless" loop. One nice thing about this design is that you can use the break statement in more than one place within the loop as needed. (Within a function, you can also return.)
How about this.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int shoesize = 13;
string answer;
int input = 0;
while (input != shoesize && answer != "no") {
cout << "Guess my shoe size!";
cin >> input;
if (input == shoesize) {
cout << "You are correct! Thanks for Playing! Would you like to play again? \n";
cin >> answer;
if (answer == "no") {
cout << "Thank you for playing!";
return 0;
}
}
}
}
Related
I am pretty new to c++ and im having an issue trying to get my program out of a loop when a string is entered for the variables cont, and answer. In python it is pretty easy to do simple checks but I am not sure what I should be doing in cpp. I tried doing a check using if(typeid(answer)) == typeid(string)) but this doesnt work. I havent tried putting a check for
'y'||'Y'||'n'||'N' for cont but im assuming it would be something like that? just check for those 4 characters?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
int main() {
unsigned seed;
char cont = 'y';
int answer = 0;
seed = time(nullptr);
srand(seed);
rand() % 100 + 1;
cout << "Lets play a math game!\n";
while(cont == 'y')
{
int num1 = rand() % 100 + 1;
int num2 = rand() % 100 + 1;
cout << "What is the result of this addition? \n " << num1 << '\n' << "+" << num2 << endl;
cin >> answer;
if (typeid(answer)==typeid(string))
{
while(typeid(answer) == typeid(string))
{
cout << "Please enter an integer!" << endl;
cin >> answer;
}
}
else if (typeid(answer) == typeid(int)) {
if (answer == (num1 + num2)) {
cout << "You are correct, would you like to play again?" << endl;
cin >> cont;
} else {
cout << "You were incorrect, would you like to try again? enter y/n" << endl;
cin >> cont;
}
} else {
answer = 0;
cout << "You did not enter an integer!\n" << endl;
cout << "Would you like to try again?" << endl;
}
}
return 0;
}
How can i check a variable type in a conditional statement in c++?
You do that already, though I'd do this instead:
#include <type_traits>
#include <iostream>
int main() {
int answer =0;
if constexpr(std::is_same_v<int,decltype(answer)>) {
std::cout << "answer is indeed an int";
}
}
However, this will always print the expected answer is indeed an int, because answer is an int not something else. If the user enters invalid input the variable answer declared as int will not turn into a std::string.
would something like if(inRange(0,200,answer)) work?
No it would not. std::cin >> answer; either succeds to read a number, or it fails and then 0 is assigned to answer. You cannot decide if valid input was entered by looking at answer only.
To check if the user entered valid input you can check the state of the stream:
#include <iostream>
#include <limits>
int main() {
int answer =0;
while(!(std::cin >> answer)){
std::cout << "please enter a number\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << answer;
}
Note that this accepts for example 42asdf as valid input, because std::cin >> answer does read 42 before it encounters something that is not a number. For something more sophisticated you can read a std::string and parse that.
I want the user to choose between playing the game again or ending the program, however when prompted, if they press 'y' the same thing gets repeated over and over instead of the whole program from the very beginning. I've tried while loops, do/while loops, if statements, rearranging the code, but nothing has worked. Any advice?
#include <iostream>
#include <string>
using namespace std;
int main(){
string animal = "fish";
string guess;
char choose = 'Y' ;
int count = 0;//keeps a running total of how many times the user
has guessed an answer.
int limit = 5;//allows user to guess only 5 times, otherwise
they loose the game.
bool out_of_guesses = false;//to check whether the user has run
out of guesses.
cout << "I am thinking of an animal.\n" << endl;
do{
while(animal != guess && !out_of_guesses){//Nested while
loop inside main loop to keep track of how many tries the user has
attempted and to validate their answers.
if(count < limit){
cout << "Can you guess what animal I am thinking of?: ";
getline(cin, guess);
count++;
if(animal != guess){
cout << "\nHmm, nope. That's not the animal I'm
thinking of." << endl;
if(count > 2 && count <5){
cout << "I'll give you a hint. It lives in
water." << endl;
}
}
}
else{
out_of_guesses = true;
}
}//End nested while loop
if(out_of_guesses){
cout << "\nI'm sorry, but you are out of guesses." <<
endl;
}
else{
cout << "\n*** Good job! You guessed the correct animal!
***" << endl;
cout << "\t\t><)))º> ❤ <º)))><\t\t" << endl;
}
//The do-while loop is there to ask the user if they wish to
play the game again.
cout << "Would you like to try again?(y/n): ";
cin >> choose;
if(choose == 'N' || choose == 'n')
break;
}while(choose == 'Y' || choose == 'y');
return 0;
}
The bool out_of_guesses = false; must be in-between while(true) and while(animal != guess && !out_of_guesses), and not outside the first while loop. Because our while loop condition is always false, and then it does enter it.
You should also reset your guess variable in-between those 2 loops, else same thing could happen (false while loop) in case of the answer is found.
Here the code with some refactoring/review, which I used the guess as upper case to handle any typography of the answer. I also removed the out of guess variable to use the count and limit one instead.
#include <iostream>
#include <string>
#include <cctype>
int main()
{
const std::string animal = "FISH";
const int limit = 5;
do
{
std::cout << "I am thinking of an animal.\n";
int count = 0;
std::string guess;
while(animal.compare(std::toupper(guess)) != 0 && count < limit)
{
std::cout << "Can you guess what animal I am thinking of?: \n";
std::cin >> guess;
count++;
if(animal.compare(std::toupper(guess)) != 0)
{
std::cout << "\nHmm, nope. That's not the animal I'm thinking of.\n";
if(count > 2)
{
std::cout << "I'll give you a hint. It lives in water.\n";
}
}
}
}//End nested while loop
if(count >= limit)
{
std::cout << "\nI'm sorry, but you are out of guesses.\n";
}
else
{
std::cout << "\n*** Good job! You guessed the correct animal! ***\n";
std::cout << "\t\t><)))º> ❤ <º)))><\t\t\n";
}
char choose = 'Y' ;
std::cout << "Would you like to try again?(y/n): ";
std::cin >> choose;
if(std::toupper(choose) == 'N') break;
} while(true);
return 0;
}
I'm trying to use std::cin whilst having one option loop back to the start. The loop works perfectly but when I add in an extra option to one of the if statements then type that in, it doesn't think that what I chose is an option.
#include <iostream>
#include <string>
#include <windows.h>
#include <chrono>
#include <thread>
using namespace std;
int main() {
string choice;
char restart;
do {
choice.clear();
cout << "Which do you take? " << endl;
cin >> choice;
if (choice == "all") {
//cout code
restart = 'y';
}
else if (choice == "dagger" || choice == "the dagger") {
choice.clear();
cout << "You pick up the dagger" << endl << endl;
return 0;
}
else {
choice.clear();
cout << "That isn't an option, pick again... "<< endl << endl;
sleep_for(1s);
restart = 'y';
}
} while (restart == 'y');
}
When I type in "dagger", it works just fine, but when I type in " the dagger" it says runs the else code, then loops back to "Which do you take" and then chooses "dagger" instantly.
You're using std::cin with the >> operator. This operator reads formatted input (words) instead of unformatted input (lines). Rather than reading "the dagger", your program is simply reading "the", and leaving "dagger" in the input buffer for later.
To read unformatted input to choice, use std::getline(std::cin, choice); instead.
It's my first time posting here, so I apologize if the post is not formatted correctly. I'm new to C++ and was looking for some help.
I can't seem to figure out what is stopping my code after roughly the 18th line. It processes the first cout and cin, but dosen't continue with the next cout?
If you enter a key, it will run through all of the conditions listed in the if/then statement and finish. However, my goal for what is here, is to have the computer generate a random number, followed by asking me for input (Y/N). Given the input, it's either supposed to generate another random number or end.
Using the compiler generate no errors, so I'm a bit dumbfounded right now as to what the issue is.
I'd appreciate any help, thank you.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<iostream.h>
int comp;
using namespace std;
int main ()
{
comp= 1+(rand() % 10);
randomnumber:
string again;
cout <<"The computer chose this random number: "<< comp << endl;
cin >> comp;
cout << "Would you like to run this again? Y/N" << endl;
cin >> again;
if((again == "y")||(again == "Y"))
{
goto randomnumber;
}
else if((again == "n")||(again == "N"))
{
cout << "OK" << endl;
}
else if((again != "y")||(again != "Y")||(again != "n")||(again !="N"))
{
cout << "Please type Y or N" << endl;
}
return 0;
}
First lets take a look at what the code should look for your requirements to be fulfilled.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<iostream.h>
//int comp; No need for comp to be a global variable here.
using namespace std;
int main ()
{
int comp;
randomnumber://if you were to use goto, the label should have been here.
comp= 1+(rand() % 10);
//randomnumber: avoid goto statements at all if possible.
//string again; No need for it to be a string.
char again;
cout <<"The computer chose this random number: "<< comp << endl;
//cin >> comp; since you want computer to generate a random no, why ask the user for it?
cout << "Would you like to run this again? Y/N" << endl;
cin >> again;
if((again == "y")||(again == "Y"))
{
goto randomnumber;
}
else if((again == "n")||(again == "N"))
{
cout << "OK" << endl;
}
else if((again != "y")||(again != "Y")||(again != "n")||(again !="N"))
{
cout << "Please type Y or N" << endl;
}
return 0;
}
Now lets take a look at how to do this in a more non-complex, simple way.
#include<iostream.h> //#include<iostream> if No such file error.
#include<time.h> // for seeding rand()
#include<stdlib.h> // for rand
using namespace std;
int main()
{
srand(time(NULL)); //seeding rand()
while(true)
{
int comp=1+(rand() % 10);
cout <<"The computer chose this random number: "<< comp << endl;
cout<<"Would you like to run this again?Y/N"<< endl;
char choice;
cin>>choice;
if ((choice == 'N')|| (choice =='n'))
{
cout<<"OK"<< endl;
break;
}
else
while(choice!='y' && choice!='Y') // forcing user to enter a valid input.
{
cout<<"Please type Y or N" << endl;
cin>>choice;
}
}
return 0;
}
I hope this helps.
Why wont the code ask the user again when I try running it if the answer is not y or n?
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char answer;
cout << "Do you like cheese?" << endl;
cin >> answer;
if ( answer != 'y' && answer != 'n' ) {
cout << endl << "Wrong answer, Try again: ";
cin >> answer;
}
return 0;
}
I understand it's not a loop but my other code seems to work fine. If the scored is less than 0, it will keep asking for a number. Why wont this code work then?
cout << "Enter the number of goals that were scored: ";
cin >> scored;
if ( scored < 0 ) {
cout << "Error: the number of goals must be greater than 0. Try again: ";
cin >> scored;
}
Change if in your if statement and replace it with while.
while ( answer != 'y' && answer != 'n' ) {
cout << endl << "Wrong answer, Try again: ";
cin >> answer;
}
Then put the rest of your code below:
//Do what you want with 'answer' here...
#include <iostream>
using namespace std;
int main(){
char answer;
cout<<"do you like cheese?"<<endl;
cin>>answer;
while((answer!='y'&&answer!='n')){
cout<<"do you like cheese?"<<endl;
cin>>answer;
}
return 0;
}