Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm just starting to learn C++ for school, and I'm having trouble completing a school project requiring the use of if/else statements. The project requires code that works as:
example of working code
My code looks like this:
#include <iostream>
using namespace std;
int ontime;
int zip;
int work;
int main()
{
cout << "Welcome to the DIG3873 System." << endl;
cout << "Did the student submit the exam on time (Y/N)? ";
cin >> ontime;
if (ontime == 'Y' || 'y') {
cout << "Did the student zip the file (Y/N)? ";
cin >> zip;
if (zip == 'Y' || 'y') {
cout << "Did the student's code work as requested (Y/N)? ";
cin >> work;
if (work == 'Y' || 'y') {
cout << "Congratulations, YOU PASS. "<< endl;
} else if (work == 'N' || 'n') {
cout << "YOU FAIL " << endl;
} else {
cout << "Please enter a valid response. " << endl;
}
} else if (zip == 'N' || 'n') {
cout << "YOU FAIL " << endl;
} else {
cout << "Please enter a valid response. " << endl;
}
} else if (ontime == 'N' || 'n') {
cout << "YOU FAIL " << endl;
} else {
cout << "Please enter a valid response. " << endl;
}
}
Unfortunately, it's not working as I would have hoped. When it runs, it lets me answer the first statement, then just drops all the other cout statements and a bunch of "YOU FAIL"s and ends the program. We haven't learned anything beyond if/else statements, so I was pretty lost looking at similar coding issues where people recommended using loops instead. Sorry for such a beginner's issue with not understanding if/else statements, thanks!
The expression zip == 'Y' || 'y' will always be true.
That's because the only comparison that's made is zip == 'Y'. The expression is really (zip == 'Y') || ('y'). That is, you test if zip is equal to 'Y'; Or if 'y', just 'y', no comparison or anything. And since 'y' is non-zero it's true.
You need to explicitly compare zip with both values: zip == 'Y' || zip == 'y'.
The same is valid for your other conditions as well.
You also have another problem, and that is you not actually reading characters but integers. If you have int variables and are using the formatted input operator >>, the input will attempt to parse the input as an integer.
To read characters you need to use char.
Related
I'd like to write a program that asks the user if he/she tends to work as a delivery service. If yes he/she should have some eligibilities. If the user have them he/she can be hired.
I've written some code, but when I compile and run it, after the user answered 2 first questions the cmd doesn't let the user to enter his/her answers for remaining questions (the cin code doesn't work anymore or as though there is no cin code.)
What's wrong with my code? Why cin doesn't work after 2 first question but it works at first 2 ones? How can I make it work?
#include <iostream>
using namespace std;
int main()
{
string answer{}, ssn1{}, a, b;
int age{0};
bool parental_consent{false}, ssn{false}, accidents{false};
cout << boolalpha;
cout << "Do you want to work as a local delivery (Y/N)? \n";
cin >> answer;
if (answer == "Y" || answer == "y")
{
cout << "Do you have any social security number(yes/no)? \n";
cin >> ssn;
ssn = ("yes" || "Yes");
cout << "How old are you? \n";
cin >> a;
cout << age;
cout << "If you're between 15 and 18 years old please answer this question: \n Do have parental "
"consent(yes/no)? \n";
cin >> ssn1;
// cout << parental_consent;
parental_consent = ("yes" || "Yes");
cout << "Have you ever had any accidents? \n";
cin >> b;
accidents = ("yes" || "Yes");
if ((age >= 18 || (age >= 16 && parental_consent)) && ssn && !accidents)
{
cout << "Yes, you can work.";
}
else if (age <= 15)
{
cout << "Sorry, your age is not eligble!\n";
}
}
else
cout << "sorry to hear that.";
cout << endl << endl << endl;
return 0;
}
From cppreference:
If the type of v is bool and boolalpha is not set, then if the value to be stored is 0, false is stored, if the value to be stored is 1, true is stored, for any other value std::ios_base::failbit is assigned to err and true is stored.
From the code, i can see that the second std::cin doesn't have boolalpha and is assigning to a bool value. This causes td::ios_base::failbit to be assigned to err, preventing other input. You have to do std::cin.clear(); to be able to use std::cin >> a; again.
If it still skips
Try using cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); after every std::cin to clear out whitespaces that causes it to return immediately.
It seems you wanted to use std::boolalpha to convert your questions into boolean. This obviously didn't work because you used it on std::cout to use it on input you need to use it on std::cin like this:
cin >> boolalpha >> ssn;
But you can't answer yes or Yes, you need to answer true or false so it's better to just std::cin >> answer and compare the string instead like this:
#include <iostream>
int main()
{
std::string answer{};
int age{ 0 };
bool parental_consent{ false }, ssn{ false }, accidents{ false };
std::cout << "Do you want to work as a local delivery (Y/N)? \n";
std::cin >> answer;
if (answer == "Y" || answer == "y")
{
std::cout << "Do you have any social security number(yes/no)? \n";
std::cin >> answer;
ssn = (answer == "yes" || answer == "Yes");
std::cout << "How old are you? \n";
std::cin >> answer;
age = atoi(answer.c_str());
if (age >= 15 && age <= 18) {
std::cout << "If you're between 15 and 18 years old please answer this question: \n Do have parental "
"consent(yes/no)? \n";
std::cin >> answer;
parental_consent = (answer == "yes" || answer == "Yes");
}
std::cout << "Have you ever had any accidents? \n";
std::cin >> answer;
accidents = (answer == "yes" || answer == "Yes");
if ((age >= 18 || (age >= 16 && parental_consent)) && ssn && !accidents)
{
std::cout << "Yes, you can work.";
}
else if (age <= 15)
{
std::cout << "Sorry, your age is not eligble!\n";
}
}
else {
std::cout << "sorry to hear that.";
}
std::cout << std::endl << std::endl << std::endl;
return 0;
}
cin>>answer;
if(answer=="yes"||"Yes"== answer)
ssn=true;
This line will only make the left of the = being true:
ssn = ("yes" || "Yes");
I was wondering how I'd be able to make my program reply to unknown answers that arent yes or no questions, when I ask them their name and they respond, they can say it is their name or its not and are given the chance to retype it until they confirm that is their name(test my code to see what I mean) but when it re asks them what their name is and says "oh, so your name is?" it just looks like the computer skips past their response and asks the question again, but i want the program to say "sorry i don't understand that" THEN re ask the question. Now what I'm wondering is how I can make it to where the computer responds with an error message to there wrong or misunderstood answer
#include <string>
using namespace std;
string Name;
}
int main() {
double age;
cout << "what is your name?"<< endl;
getline(cin, Name);
cout << "your name is " << Name << "?, is that correct? Y/N"<< endl;
string answer;
getline(cin, answer);
if (answer == "yes") {
cout << "thanks for the information" << endl;
}
if (answer == "no"){
do {
cout << "oh ok, what is your name then?"<< endl;
getline(cin,Name);
cout<< "oh so your name is " + Name << "? Y/N"<< endl;
getline(cin, answer);
}
while(answer <= "no");{
}
}
cout << "how old are you?" << endl;
cin >> age;
cout << "your name is "<< Name << " and you are " << age << " years old"<< endl;
return 0;
}
You are on the right track using "if" statements and "while" loops. You just need to improve your understanding of the while loop & if-else statements, then with a few edits you can get your code working.
Firstly, you are prompting the user for "Y/N", but then you are trying to test for "yes" or "no". This is will be very confusing for the user, who is trying to enter a 'Y' or a 'N' and not getting anywhere. You should pick one or the other. In this case I will assume you want to proceed with "Y/N".
First, take a look at your use of the while loop.
For the while condition, you have used a <= sign, which is testing for "less than or equal to". In this context, you probably want to test for equality (==) or non-equality (!=).
You haven't placed any statements within the body of the while loop (i.e. inside the curly braces {} ). A while loop will only execute the code within the curly braces.
For your program, you only need to re-prompt the user if they answer with anything other than a 'Y'. Then you want to keep prompting the user until they enter a 'Y'... a while loop is perfect for this. To make this work, your condition for the loop should be (assuming you want to test for upper and lower case input):
while (answer != "y" || answer != "Y") {
}
Now, any code you put inside the curly braces {} will continue to loop until the user inputs 'y' or "Y".
Next, have a look at your use of if statements.
Your first if statement tests the input for "yes".
Your second if statement tests the input for "no".
The problem with this, is that if neither "yes" or "no" are input, no code will be executed.
The key is changing your second "if" statement to an "else". The "else" will act as a catch all - if anything is entered outside of the program's scope, the else statement will catch it and re-prompt the user..
Finally you want to place the if-else statements inside the while loop - then you can be sure the user will continue to be prompted until they enter a 'Y'.
I have altered your code so that it now provides the desired behavior:
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "What is your name?" << endl;
string name {};
getline (cin, name);
cout << "Your name is: " << name << ". Is that correct? Y/N: " << endl;
string answer {};
getline(cin, answer);
while (answer != "y" && answer != "Y") {
if (answer == "n" || answer == "N") {
cout << "Oh, ok, what is your name then? " << endl;
getline (cin, name);
cout << "Oh, so your name is " << name << "? Y/N: " << endl;
getline (cin, answer);
}
else {
cout << "Sorry... I don't understand that. Please enter 'Y' or 'N'..." << endl;
cout << "Your name is: " << name << ". Is that correct? Y/N: " << endl;
getline (cin, answer);
}
}
cout << "How old are you? " << endl;
int age {};
cin >> age;
cout << "Thanks, so your name is "<< name << " and you are " << age << " years old" << endl;
return 0;
}
Everything is working fine in this program except when it reaches getline() after cout<<"From Date: ";. At this point no matter if I give input or simply hit enter without input, I have to hit enter twice to proceed further. I tried removing cin.ignore() but it causes more problem by jumping over the first getline(). Here is the snippet which is causing this problem-
int main() {
Date d1;
int choice;
cout << "\nEnter choice: ";
cin >> choice;
cin.ignore(numeric_limits < streamsize > ::max(), '\n');
switch (choice) {
case 1:
d1.diffbw();
break;
default:
cout << "Wrong choice";
}
return 0;
}
void Date::diffbw() {
Date current, ref;
string choice;
cout << "\n Type 'man' to enter date manually else hit Enter to insert current date!";
do {
cout << "From Date:";
getline(cin, choice);
if (choice == "man")
current.getdate(); //getdate() assigns day, month and year in object current
else if (choice.empty())
current = sysDate(); //sysDate returns system date
else {
cout << "\n Wrong Choice!";
cout << "\n Enter Again?(y/n): ";
getline(cin, choice);
}
} while (choice == "y" || choice == "Y");
do {
cout << "To Date:";
getline(cin, choice);
if (choice.empty())
ref = sysDate();
else if (choice == "man")
ref.getdate();
else {
cout << "\n Wrong Choice!";
cout << "\n Enter Again?(y/n): ";
getline(cin, choice);
}
} while (choice == "y" || choice == "Y");
current.calcAge(ref); //calcAge() calculates difference between two given dates.
cout << "\n Difference: ";
cout << abs(current.day) << " day(s) " << abs(current.month) << " month(s) " << abs(current.year) << " year(s)";
}
P.S.- I am using g++ compiler on windows.
Edit: I posted the whole function here as many people are having difficulty in understanding the context here. I also corrected the 'cin.ignore()' syntax as suggested by #john. I am trying to calculate difference between two given dates.
The second 'do while' loop works without any bug although it is completely synonymous with the first one.
It might be because you are first trying to get a value by calling cin.getline() and afterwards the program is done but is waiting for confirmation and it gets the confirmation by you pressing enter.
Basically
Enter Value: 5 //Presses enter
Press any key to exit window.
Your statement
cout<<"\n\n From Date:";
is strange and probably wrong, since the std::cout stream is generally buffered.
You should use std::cout << "From date:" << std::endl; and read a good C++ programming book and check in this C++ reference that you are correctly using every function or feature from the C++ standard library.
If you compile with a recent GCC, I recommend enabling all warnings and debug info, so compiling with g++ -Wall -Wextra -g. Then use your debugger, e.g. GDB.
If your computer runs some Linux or POSIX system, you could be interested in using GNU readline: then the input line becomes user-editable. You might also want to code a graphical application with Qt.
Everything is working fine in this program
How did you check that? What debugger did you use? What test cases do you have? Did you try to type something with spaces, e.g. today's date as the user input? What did happen?
I slightly modified your program to avoid relying on the Date class, which you did not define:
#include <string>
#include <iostream>
#include <limits>
#include <math.h>
#include <stdio.h>
using namespace std;
void diffbw();
int main() {
int choice;
cout << "\nEnter choice: ";
cin >> choice;
cin.ignore(numeric_limits < streamsize > ::max(), '\n');
switch (choice) {
case 1:
diffbw();
break;
default:
cout << "Wrong choice";
}
}
void diffbw() {
string choice;
cout << "\n Type 'man' to enter date manually else hit Enter to insert current date!";
do {
cout << "From Date:";
getline(cin, choice);
cout << "choice";
if (choice == "man") {
}
else if (choice.empty()) {
}
else {
cout << "\n Wrong Choice!";
cout << "\n Enter Again?(y/n): ";
getline(cin, choice);
}
} while (choice == "y" || choice == "Y");
do {
cout << "To Date:";
getline(cin, choice);
if (choice.empty()) {
}
else if (choice == "man") {
}
else {
cout << "\n Wrong Choice!";
cout << "\n Enter Again?(y/n): ";
getline(cin, choice);
}
} while (choice == "y" || choice == "Y");
cout << "\n Difference: ";
}
and I don't see the same phenomenon you describe. That is, I don't need to press Enter twice. Please consider making your problematic program more minimal, and at the same time complete.
This is my code.
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "Welcome to Starbucks! What would you like to order?" << endl;
cout
<< "Before you select your order, would you like to look at your wallet to see how much money you have on you right now? "
<< flush;
string input;
cin >> input;
if (input == "Yes" || input == "yes") {
cout << " " << endl;
cout << "OK. You have $18.90 in your wallet. Now showing menu. "
<< flush;
}
else {
cout << " " << endl;
cout << "OK. Now showing menu. " << endl;
}
cout << "\n\n\tDrinks:\n\nHot Coffees\nHot Teas\nHot Drinks\nFrappuccino Blended Beverages\nCold Coffees\n\n\tFood:\n\nHot Breakfast"
"\nBakery\nLunch\nSnacks & Sweets\nYogurt & Custard\n\n\tMerchandise:\n\nDrinkware" << endl;
string option;
cout << "Select an option from one of these sections. Type your selection here: " << flush;
getline(cin, option);
if (option == "Hot Coffees" || option == "hot coffees" || option == "Hot coffees" || option == "hot Coffees") {
cout << "Welcome to the Hot Coffees section. Here is a list of all the hot coffees we sell:\n\nAmericanos:\n\nCaffè Americano\nStarkbucks Blonde Caffè Americano\n" << endl;
}
return 0;
}
At the very end, when I decide to use a getline function (I want to get the input of the user to use in if statements), I am unable to type into my console for an unknown reason, therefore making me unable to get the user's input. I have already tried cin.ignore(); , and although this let me type into the console, after I typed the words "Hot Coffees", it didn't print out "Welcome to the Hot Coffees section.", even though I programmed my if statement to print this out if(option == "Hot Coffees"). If you can figure this out, thank you! If you can't, I am certainly glad you at least tried, and I will be just as thankful.
It's likely that you still have a \n in your input buffer, so when you reach getline() it's reading that as the delimiting character, and returning that as input for you. I think that std::flush might do something different than you think it does. This is a helpful read: https://www.cplusplus.com/reference/ostream/flush-free/
Here's a line of code that's useful when dealing with while user input on the console in C++, It gets every character in the input buffer until it finds a \n.
while (cin.get() != '\n');
Best of luck to you!
It's because C++ doesn't consider spaces, so try typing cin.ignore(); after getline function. And you made mistakes in the if section, type this....
if (option == "Hot Coffees" || "hot coffees" || "Hot coffees" || "hot Coffees") {
cout << "Welcome to the Hot Coffees section. Here is a list of all the hot coffees we sell:\n\nAmericanos:\n\nCaffè Americano\nStarkbucks Blonde Caffè Americano\n" << endl;
}
Overall problem I'm having: I'm misunderstanding how to properly validate user input in a menu selection using loops/if-else-if sort of logic. I need to figure out what I'm doing conceptually wrong, more than technically wrong (as we have very specific rules of how to approach our programs in class).
Problem #1 = When the program starts there are two options to the user. There obviously needs to be a response that a user has put in a invalid character if neither of the two options is picked. My problem is that when I’m on the invalid selection screen it only allows me to hit ‘P’ to start the game, and not ‘Q’ to end the game. Something in my loop is only accepting ‘P’ as valid input to push the program forward.
I've tried switching between do/while loops and if/else if statements. The do/while loop has provided the least amount of problems, while still retaining some.
I'm only in my second programming class so I probably can't give a better detailed answer than I've tried different loops and moved small bits of code around, sorry.
I’m only going to post the int main() of the program as that contains the menu i’m having problems with. There are additional functions that have user input with similar issues, but if I fix my conceptual mistake here, I can fix it there after.
int main()
{
char Sel;
int compChoice;
int playerChoice;
cout << "\n";
cout << "ROCK PAPER SCISSORS MENU" << endl;
cout << "------------------------" << endl;
cout << "p) Play Game" << endl;
cout << "q) Quit" << endl;
cout << "Please enter your choice:" << endl;
cin >> Sel;
if (Sel == 'q' || Sel == 'Q')
{
cout << "You have chosen to exit, thanks for playing" << endl;
}
do
{
if (Sel == 'p' || Sel == 'P')
{
playerChoice = getPlayerChoice();
compChoice = getComputerChoice();
if (isPlayerWinner(compChoice, playerChoice))
{
cout << "Winner Winner Chicken dinner" << endl;
}
else if (!isPlayerWinner(compChoice, playerChoice))
{
cout << "You lose this round" << endl;
}
else if (isTie(compChoice, playerChoice))
{
cout << "You have Tied" << endl;
}
else
{
cout << "Thanks for playing" << endl;
return 0;
}
}
else
{
cout << "Invalid selection, please try again by hitting 'p' or 'q'." << endl;
cin >> Sel;
}
} while (Sel != 'q' || Sel != 'Q');
system("PAUSE");
return 0;
}
Thanks for your time!
The culprit is this line at the end on the do/while loop.
while (Sel != 'q' || Sel != 'Q');
Should be the following.
while (Sel != 'q' && Sel != 'Q');