Why is the User Unable to Give Their Input - c++

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

Related

How do I make my program only react to yes or no answers?

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

Why do I need to press Enter twice after getline()?

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.

Creating rudimentary user input validation for menus (using basic while/do-while etc loops)

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');

c++ While loops prints the couts twice

In my code, the while loop prints the cout twice when it should print it once, as well as the function's couts. I don't understand why it's doing this - it is supposed to display
What would you like to do?
Deposit
Withdraw
Cancel
But, it displays that twice.
while (yesNo == 'Y') {
cout << "What would you like to do?"
<< endl
<< endl;
menu();
getline(cin, bankChoice);
if (bankChoice == "Withdraw")
{
withdrawTotal = withdraw(bankAmount);
bankAmount = withdrawTotal;
cout << "You now have $"
<< bankAmount
<< " in your account."
<< endl;
cout << "Would you like to do anything else?"
<< endl
<< "Y/N: ";
cin >> yesNo;
}
if (bankChoice == "Deposit")
{
depositTotal = deposit(bankAmount);
bankAmount = depositTotal;
cout << "You now have $"
<< bankAmount
<< " in your account."
<< endl;
cout << "Would you like to do anything else?"
<< endl
<< "Y/N: ";
cin >> yesNo;
}
if (bankChoice == "Cancel") {
return 0;
}
}
That is the loop I am using. If additional code is needed I can post it as well, but this is the part that is causing the issue. I've tried the code without it and it works fine, but I'd like to get the code to loop until the user enters 'N'.
You are using both std::getline and operator>> to read from std::cin. operator>> does not consume the trailing newline, so the next call to std::getline() will immediately read the following newline and interpret it as an empty line of text that was entered. This will run through the loop, and go back up to the top, for the second prompt.
Never use operator>> with std::cin when you intend to read a single line of text.
The following short example demonstrates this point:
#include <iostream>
#include <string>
int main()
{
char c;
std::string l;
std::cin >> c;
std::cout << "A line of text please: ";
std::getline(std::cin, l);
}
Run it, enter "Y", and try to figure it out, yourself, why the program terminates immediately.
Once again: don't use operator>> to read lines of text from std::cin. It is a recipe for grief, and bugs.
In addition to Sam's answer, I'd like to recommend that you extract common functionality outside your two if statements:
std::string yesNo;
while (yesNo.compare("Y") == 0) {
cout << "What would you like to do?"
<< endl
<< endl;
menu();
getline(cin, bankChoice);
if (bankChoice == "Cancel")
return 0;
if (bankChoice == "Withdraw") {
withdrawTotal = withdraw(bankAmount);
bankAmount = withdrawTotal;
}
if (bankChoice == "Deposit") {
depositTotal = deposit(bankAmount);
bankAmount = depositTotal;
}
cout << "You now have $"
<< bankAmount
<< " in your account."
<< endl;
cout << "Would you like to do anything else?"
<< endl
<< "Y/N: ";
std::getline(std::cin, yesNo);
}

Im creating a text based adventure game and need an alternative to using GOTO

How can I properly use a do, while, or for loop of some kind to prevent the user from entering anything else other than the answer "1" or "2"?
If they don't, the program should tell them they cannot do that and then return them to the previous question.
#include <iostream>
#include "Options.h"
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
cout << "\tWelcome to my text adventure game\n" << endl;
cout << "Please enter your characters Name: ";
string name;
cin >> name;
cout << "\nWelcome " << name << endl;
cout << "\nPlease choose the side you would like to play in - ";
Options OptionsObject;
OptionsObject.optionsSide();
string answer;
while(answer != "quit") {
cin >> answer;
cout << answer << endl;
}
if ( answer == "1" ) {
cout << "You chose the good side. Let the game begin\n " << endl;
cout << "You are located in a city named after the warrior who saved it from the evil\nmany years ago. The city of Redshore. " << endl;
cout << "You are no ordinary man in the City of Redshore. You are the king who rules it\nYou are seen as King of Justice, a good king.\nOne who only want what is best for his people" << endl;
cout << "but also a troubled man. You experienced something traumatizing when you\nwere a just a little boy, but no one knows about it,\nno one but yourself that is " << endl;
} else if( answer == "2" ) {
cout << "hey there" << endl;
}
}
Seen that this problem would be in all the choose the user will do during the game I will make an external function, to let the user choose. Maybe a static class working in this way.
int ans = Answer.getUserAnswer(2,"[1/2]>");
and this should work in this way:
public static int getUserAnswer(int max =1,string message="[1/1]>")
{
int ans = 0;
while(ans==0){
cout<<message<<" ";
cin >> answer;
if(answer>0 and answer<=max) return ans;
cout<<"\tnot a valid choose\n";
ans=0;
}
}
and you will have in your ans one of the value you expect, and it will print "not a valid choose" if the answer is not between the one you expect, and you can do this even with 10 answers, calling it by default expect you to give him just the number one.
I used it in a console game I made ;)
Hope is useful
EDIT
int getUserAnswer(int max =1,string message="[1/1]>")
{
int ans = 0;
while(ans==0){
cout<<message<<" ";
cin >> answer;
if(answer>0 and answer<=max) return ans;
cout<<"\tnot a valid choose\n";
ans=0;
}
}
and to request this code in your code:
cout << "\nWelcome " << name << endl;
cout << "\nPlease choose the side you would like to play in - ";
Options OptionsObject;
OptionsObject.optionsSide();
int answer =getUserAnswer(2,"[1/2]>");
if (answer == 1){
cout << "You chose the good side. Let the game begin\n " << endl; cout << "You are located in a city named after the warrior who saved it from the evil\nmany years ago. The city of Redshore. " << endl; cout << "You are no ordinary man in the City of Redshore. You are the king who rules it\nYou are seen as King of Justice, a good king.\nOne who only want what is best for his people" << endl; cout << "but also a troubled man. You experienced something traumatizing when you\nwere a just a little boy, but no one knows about it,\nno one but yourself that is " << endl;
}
else if(answer == 2){
cout << "hey there" << endl;
}
You should put the line where you read the input in a do loop that loops while the answer given by the user is invalid.
So, your do loop should be:
string answer;
cin >> answer;
// loop while answer is neither "1" nor "2"
while( answer != "1" && answer != "2" ) {
cout << "Please enter a 1 or a 2. You entered " << answer << endl;
cin >> answer;
}