C plus plus wont loop - c++

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;
}

Related

How can i check a variable type in a conditional statement in c++?

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.

How to repeat program if user says they want to play again?

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;
}
}
}
}

Stumped on why my code won't output a text?

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.

loop repeats without prompting the user again?

I have this snippets of code from my original long program, and as much as it looks simple, it doesn't work correctly! I am brand-new to c++ language, but I know in Java that would be the way to do it (Regardless of the syntax).
Simply put, this should ask the user for an input to answer the following multiplication (5*5), however, it should also check if the user entered a wrong input (not number), keep asking the user again and again... Somehow, it keeps running forever without taking a new input!!
I hope to get, not only an answer, but also a reason for such an error!
int main() {
int userAnswer;
bool isValidAnswer = true;
cout << 5 << " * " << 5 << " = ";
cin >> userAnswer;
cin.ignore();
do {
if (cin.fail()) { //user input is not an integer
cout << "Your answer is not valid! Please enter only a natural number: ";
cin >> userAnswer;
cin.ignore();
} else {
isValidAnswer = false;
}
} while (isValidAnswer);
return 0;
}
Well you need to clear the error state before accepting new input. Call cin.clear() then cin.ignore() before trying to read input again.
I would do something like.
cout << "Enter a number: ";
cin >> number;
while(cin.fail())
{
cin.clear();
cin.ignore(1000, '\n'); //some large number of character will stop at new line
cout << "Bad Number Try Again: ";
cin >> number;
}
First, cin.fail() is not going to adequately check if your answer is a natural number or not with the type set to int (could also be negative).
Second, your boolean isValidAnswer is really checking if it's is an invalid answer.
Third (and most importantly), as another answer suggests, you should put in cin.clear() to clear the failure state, and then followed by cin.ignore(), which will remove the failed string from cin.
Fourth, cin will only check if an int exists somewhere in the string. You'll need to perform your own string comparison to determine if the entire input is a int (see answer below, based on this answer).
Updated:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
bool isNum(string line)
{
char* p;
strtol(line.c_str(), &p, 10);
return *p == 0;
}
int main() {
int userAnswer;
string input;
bool isInvalidAnswer = true;
cout << 5 << " * " << 5 << " = ";
while (isInvalidAnswer) {
if (!(cin >> input) || !isNum(input)) {
cout << "Answer is not a number! Please try again:\n";
cin.clear();
cin.ignore();
}
else {
userAnswer = atoi(input.c_str());
if (userAnswer < 0) { //user input is not an integer
cout << "Answer is not a natural number! Please try again:\n";
} else {
isInvalidAnswer = false;
}
}
}
cout << "Question answered!\n";
return 0;
}

Validating user input of a number

Trying to create a while loop that will re-ask to enter correct input. In this case, the correct input needs to be a number. When I test it and put in a non-number answer, it ends the program. The while loop isn't working.
if (variableQuestionsVf == "Yes" || variableQuestionsVf == "yes")
{
cout << "Input final velocity (in m/s): " ;
while (cin >> finalVelocity)
{
istringstream s(sVf);
s >> value;
if (value <= 0 || value >= 0) //Validating input for final velocity
break;
cout << "Please enter final velocity (in m/s): " ;
}
}
Is there an easier way?
I think you are validating your input incorrectly. Try doing something like this:
#include <iostream>
#include <limits>
int main()
{
int x;
std::cin >> x;
while(std::cin.fail())
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
std::cout << "Bad entry. Enter a NUMBER: ";
std::cin >> x;
}
}
Source