Function call not working, but console still allowing input. - c++

The menu pops up at first which shows a list of items a user can buy. Then the user is asked whether they want to checkout their items or continue shopping. When the user types "no" after being prompted, instead of menu(); being called to bring them back to the menu. Nothing happens. I'm able to type in the console but nothing else shows up.
Here is the code for the question which is in a different function:
cout << "Would you like to checkout?" << endl;
cout << "Type 'yes' to continue or 'no' to keep shopping." << endl;
cin >> answer;
if (answer == "yes") {
checkout(mpadNum, mouseNum, hsetNum, keyboardNum, laptopNum, pcNum);
}
else if (answer == "no") {
menu(mpadNum, mouseNum, hsetNum, keyboardNum, laptopNum, pcNum);
}
Here is the code for part of the menu function if needed:
void menu(int mpadNum, int mouseNum, int hsetNum, int keyboardNum, int laptopNum, int pcNum) {
int *mpadQty;
string answer;
string option;
if (file.is_open()) {
cout << file.rdbuf();
}
cout << " " << endl;
cout << "What would you like to purchase?" << endl;
cout << "Please type your selection." << endl;
cin >> option;
if (option == "mousepad") {
cout << "How many mousepads would you like?" << endl;
cin >> mpadNum;
}
mpadQty = new int(mpadNum);
mpadAmnt += *mpadQty;
cout << "Your selection has been added to the cart" << endl;
cout << "Type anything to continue." << endl;
cin >> answer;
cart(mpadNum, mouseNum, hsetNum, keyboardNum, laptopNum, pcNum);
}

Here is a debugging hint. Try printing out the answer after your line cin >> answer.
cout << "answer->" << answer << "<-" << endl;

Related

How can I return user to original switch menu from do-while loop?

how can I get user to go back to original switch menu once the user selects N at the end. When user selects N, would I use another loop to get them back to original menu? Any help is greatly appreciated.
cout << "Total Chips: " << chips << endl;
cout << "1) xxxxx" << endl;
cout << "2) xxx" << endl;
cout << "Please enter an option" << endl;
int option;
cin >> option;
switch(option)
{
case 1:
{
char again;
do
{
/* code
*/
cout << "Would you like to play again? Y/N" << endl;
cin >> again;
}while(towlower(again) == 'y'); // I'm not sure whether to use another do-while loop.
When user selects N, would I use another loop to get them back to original menu?
Yes, one that is put around the original menu, eg:
bool keepRunning = true;
do {
cout << "Total Chips: " << chips << endl;
cout << "1) xxxxx" << endl;
cout << "2) xxx" << endl;
cout << "Please enter an option" << endl;
int option;
cin >> option;
switch (option)
{
case 1:
{
char again;
do
{
/* code
*/
cout << "Would you like to play again? Y/N" << endl;
cin >> again;
}
while (again == 'y' || again == 'Y');
break;
}
...
}
}
while (keepRunning);

Verifying User Input as Integer: User has to enter input twice

I am prompting the user to enter an integer value. When the value is incorrect, the program works. However, when the user enters an integer input, the user needs to enter the input twice.
I looked at other tutorials on how to use the while loop to catch erroneous input, and that part worked for me. However, the integer values need to be entered twice in order for the program to run.
#include <iostream>
using namespace std;
int main() {
cout << "*************************************************" << endl;
cout << "******************|DVD Library|******************" << endl;
cout << "*************************************************" << endl;
cout << "1.\tAdd DVD" << endl;
cout << "2.\tDelete DVD" << endl;
cout << "3.\tSearch DVD" << endl;
cout << "4.\tList All DVDs in the Library" << endl;
cout << "5.\tAdd DVD to Favorites List" << endl;
cout << "6.\tDelete DVD from Favorites List" << endl;
cout << "7.\tSearch DVD in Favorites List" << endl;
cout << "8.\tList All DVDs in Favorites List" << endl;
cout << "9.\tQuit" << endl;
cout << "*************************************************" << endl;
int input;
cin >> input;
while (!(cin >> input)) {
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Please enter an integer --> " << flush;
}
if (input < 1 || input > 9) {
cout << "Invalid input! Please try again!" << endl;
}
return 0;
}
You ask for the input twice:
cin >> input;
while(!(cin >> input )){
Removing the first line might make it work you intended.
'The user has to enter the input twice' Look at your code
int input;
cin >> input;
while(!(cin >> input )){
How many times do you ask the user for input?
You'd have more luck with this
int input;
while(!(cin >> input )){
Your error recovery code looks reasonable, haven't tested it though.
int input;
while (cout << "Your choice: ",
!(cin >> input) || input < 1 || 9 < input)
{
cin.clear();
while (cin.get() != '\n');
cerr << "Invalid input! Please try again!\n";
}
Thanks everyone! The "cin >> input;" line was unnecessary. At first, I left it there because it would actually tell the user the error message if the user entered a numeric input such as a double. So, if the user entered something like 3.3, the program would display an error message that I specified ("Please enter an integer" line). However, the program in this case (when there is a double) asks the user to prompt for the integer input twice and then continues the program. When I delete the said unnecessary line, the program accepts a double input, but what it does, it takes the numeric value before the decimal point and uses it as the integer. So, a value of 1.2 is recorded as 1 when I tested it. I'm unsure why this phenomenon happens, but the program works otherwise. Maybe it accounts for human error?
#include <iostream>
using namespace std;
int main() {
cout << "*************************************************" << endl;
cout << "******************|DVD Library|******************" << endl;
cout << "*************************************************" << endl;
cout << "1.\tAdd DVD" << endl;
cout << "2.\tDelete DVD" << endl;
cout << "3.\tSearch DVD" << endl;
cout << "4.\tList All DVDs in the Library" << endl;
cout << "5.\tAdd DVD to Favorites List" << endl;
cout << "6.\tDelete DVD from Favorites List" << endl;
cout << "7.\tSearch DVD in Favorites List" << endl;
cout << "8.\tList All DVDs in Favorites List" << endl;
cout << "9.\tQuit" << endl;
cout << "*************************************************" << endl;
int input;
while (!(cin >> input)) {
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Please enter an integer --> " << flush;
}
if (input < 1 || input > 9) {
cout << "Invalid input! Please try again!" << endl;
}
return 0;
}

function for validation input c++ simple [closed]

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 6 years ago.
Improve this question
to some this might seem simple, but to me I can't really seem to figure out why this isn't working. I know I could just copy and paste every time inside the while loop to get the result I want, but I've been told that if you have to repeat something more than one time to write a function! My code will double print the number and even though someone would type 8 it will still go into the while loop. Hoping someone can explain why this is happening to me.
int main()
{
int option = selectionHelper();
cout << selectionHelper() << endl;
cout << endl;
if(option == 8)
{
cout << "Exiting program..." << endl;
cout << endl;
cin >> option;
}
while (option != 8)
{
if (option == 1){
cout << selectionHelper() << endl;
cout << endl;
cin >> option;
}else if(option == 2){
cout << selectionHelper() << endl;
cout << endl;
cin >> option;
}else if(option == 3){
cout << selectionHelper() << endl;
cout << endl;
cin >> option;
}else if(option == 4){
cout << selectionHelper() << endl;
cout << endl;
cin >> option;
}else if(option == 5){
cout << selectionHelper() << endl;
cout << endl;
cin >> option;
}else if(option == 6){
cout << selectionHelper() << endl;
cout << endl;
cin >> option;
}else if(option == 7){
cout << selectionHelper() << endl;
cout << endl;
cin >> option;
}else{
cout << "Invalid input... Please try again..." << endl;
cout << endl;
cout << selectionHelper() << endl;
cout << endl;
cin >> option;
}//end else if statement
}//end while loop
}//end function main
and now for my function:
int selectionHelper()
{
int option;
cout << "1. Initialize seating for new performance." << endl;
cout << "2. View seating chart." << endl;
cout << "3. Reserve seats." << endl;
cout << "4. Calculate tickets remaining in row." << endl;
cout << "5. Calculate tickets remaining in theater." << endl;
cout << "6. Calculate total tickets sold." << endl;
cout << "7. Calculate ticket sales." << endl;
cout << "8. Exit program." << endl;
cout << "Option: " << endl;
cin >> option;
return option;
}//end selectionHelper
Thank you for looking at my post!
This answer and others will tell you what code to write to fix your problem. If you should encounter similar problems in the future, try walking through your code with a debugger. (Experience helps too.) Regarding code redundancy: first, it's good that you used the selectionHelper() method. That shows you have good instincts. Here's what you can do further:
Look for lines of code that are the same or differ only by a variable.
Consider condensing them in the following ways:
Can you use a for-loop?
Can you put the code in a method (possibly abstracting out a variable?)
Can you use a broader conditional statement? (That's what you have going on here: if a number is 1, 2, 3, 4, 5, 6, or 7, it's also >0 and <7. That's why we have ranges.)
The program keeps going when they enter 8 because you ask them to input a number after they input 8! So your first chunk of code can be simpler:
int option = selectionHelper();
cout << option << endl <<endl; // <-- output option, don't call selectionHelper() here again, that's why you get double printing
if(option == 8)
{
cout << "Exiting program..." << endl;
cout << endl;
//cin >> option; // <-- don't input here again!
}
The key here to simplifying your code is to recognize that you only write different code in a few cases. So, here's your while loop:
while (option != 8)
{
if (option > 0 && option < 8){
cout << selectionHelper() << endl;
cout << endl;
cin >> option;
}else{
cout << "Invalid input... Please try again..." << ends << endl;
cout << selectionHelper() << endl << endl;
cin >> option;
}//end else if statement
}
You must modify your code in the following ways:
int option = selectionHelper();
cout << option << endl;
And also:
if(option == 8)
{
cout << "Exiting program..." << endl;
}
You can simplify your code down to (using partly the simplification made by cuniculus but also fixing the mistake in your own code of wrong using option):
#include <iostream>
using namespace std;
int selectionHelper()
{
int option;
cout << "1. Initialize seating for new performance." << endl;
cout << "2. View seating chart." << endl;
cout << "3. Reserve seats." << endl;
cout << "4. Calculate tickets remaining in row." << endl;
cout << "5. Calculate tickets remaining in theater." << endl;
cout << "6. Calculate total tickets sold." << endl;
cout << "7. Calculate ticket sales." << endl;
cout << "8. Exit program." << endl;
cout << "Option: " << endl;
cin >> option;
return option;
}//end selectionHelper
int main()
{
int option = selectionHelper();
while (option != 8)
{
if (option > 0 && option < 8){
option = selectionHelper();
}else{
cout << "Invalid input... Please try again..." << ends << endl;
option = selectionHelper();
}//end else if statement
}
cout << "Exiting program..." << endl;
return 0;
}//end function main
Your mistake was basically in calling selectionHelper too many times, when only once is needed to set the option variable. You have a similar thing going on in your whole if-else structure - but I'll leave it up to you to fix that if needed, the solution is the same.

Program Infinitely Looping

This is a snippet of the code from my program. The function getMenuChoice() runs successfully on Visual Studio when I enter integers but when I enter a character it goes into an infinite loop. I was told that my program does not have to account for the user entering a character but yet when I submit it, the grading machine tells me it "exceeded the allowed length". Besides the fact it does not account for characters, I am not sure what is wrong with the function. If I was to account for characters though, how would I do that?
// Calls header and menu.
int main() {
printHeading();
getMenuChoice();
}
//Prints the header.
void printHeading() {
cout << "*******************************" << endl
<< " Birthday Calculator " << endl
<< "*******************************" << endl << endl;
}
//Prints the closer.
void printCloser() {
cout << endl;
cout << "****************************************************" << endl
<< " Thanks for using the Birthday Calculator " << endl
<< "****************************************************" << endl
<< endl;
}
void printMenu() {
cout << endl << endl;
cout << "Menu Options" << endl
<< "------------" << endl;
cout << "1) Determine day of birth" << endl;
cout << "2) Print the next 10 leap years" << endl;
cout << "3) Determine birthdays for the next 10 years" << endl;
cout << "4) Finished" << endl << endl;
cout << "Choice --> ";
}
//Gets user's menu choice.
int getMenuChoice() {
int choice;
printMenu();
cin >> choice;
//If user does not select 4, it selects their menu choice.
while (choice != 4) {
if (choice == 1) {
determineDayOfBirth();
}
else if (choice == 2) {
print10LeapYears();
}
else if (choice == 3) {
print10Birthdays();
}
//User did not enter a valid choice and the following prints.
else {
cout << "Invalid menu choice" << endl;
}
//Allows the user to enter another choice
//after they have executed one choice.
printMenu();
cin >> choice;
}
//Prints closer when user chooses 4.
printCloser();
return 0;
}
Its been awhile since I played with C++ but here is a shot.
int choice;
printMenu();
cin >> choice;
ValidateOption(choice);
// Then if you want them to be able to pick again you can just do it over again
printMenu();
cin >> choice;
ValidateOption(choice);
function ValidateOption(int choice){
//If user does not select 4, it selects their menu choice.
while (choice != 4) {
if (choice == 1) {
determineDayOfBirth();
}
else if (choice == 2) {
print10LeapYears();
}
else if (choice == 3) {
print10Birthdays();
}
//Prints closer when user chooses 4.
else if (choice == 4){
printCloser();
return 0;
}
//User did not enter a valid choice and the following prints.
else {
cout << "Invalid menu choice" << endl;
// Make the user select again because the input was invalid
printMenu();
cin >> choice;
}
}
}
You can try to flush cin like this:
cin >> choice;
cin.clear();
cin.ignore(INT_MAX);
or as suggested by #user4581301
cin.ignore(numeric_limits<streamsize>::max(), '\n');

Why getline does not work in a switch, and cin does not take the data appropriately?

I need to take in the make model and years of the car the particular product fits. The program is going to write a file with text in it that will be an outline of the html. I need with the crucial information inserted into the correct spots to quickly be able to add products to our web page. When I use a switch statement or if statements to separate the categories of the products, the input gets messed up and does not let me answer one of the questions. I can't just use cin because I need to take dates that look like "2008 - 2009 - 2010 - 2011".
Here is what I've got so far! This one is just regular cin, I have tried getline you could quickly c I started yesterday and I'm pretty new so forgive me if this is an easy fix, but I cant find anything.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void proinfo();
int main()
{
//Sytem Information
system("TITLE This is a Beta of My Product Information Template Version 0.0.2");
//I'm using this as a welcome screen to inform users of new improvements on patches and other pertinent information to the users
cout << "Welcome To My Product Information Template Maker!!! \n It Is Still In Development" << endl;
cout << "\n\nworking features are:" << endl << "\t-None\n" << endl;
system("PAUSE");
system("CLS");
proinfo();
}
void proinfo()
{
//Declare Variables here
int loop(1), protype;
char make[256], model[256], year[256];
string getinput;
while(loop==1)
{
//This is the first menu the user sees where they have to choose what type
//of products users will be adding
system("CLS");
cout << "Welcome to My Product Information Template Version 0.0.0" << endl;
cout << "Please select the number of the product" << endl;
cout << "type you will be ading!\n" << endl;
cout << "1.Fe - Fe2 Moldings" << endl;
cout << "2.CF - CF2 Moldings" << endl;
cout << "What would you like to do? ";
cin >> protype;
if(protype==1)
{
//FE - FE2 Molding
system("cls");
cout << "You have selected" << endl;
cout << "Fe - Fe2 Moldings\n" << endl;
cout << "Please Enter the Make of the molding" << endl;
cin >> make;
cout << "Please Enter the Model of the molding" << endl;
cin >> model;
cout << "Please Enter the Years this molding fits" << endl;
cin >> year;
cout << "You have just created a template for a(n)" << year << " " << make << " " << model << endl;
cout << "Check My Documents For a file called Fe-Fe2template.txt" << endl;
//Asks to quit or restart
cout << "Would you like to make another tempalte?" << endl;
cin >> getinput;
if(getinput=="yes")
{
cout << "Great, Lets keep working!" << endl;
//End of If statement
}
system("PAUSE");
}
if(protype==2)
{
//CF - CF2 Molding
system("cls");
//Asks to quit or restart
cout << "Would you like to make another tempalte?" << endl;
cin >> getinput;
if(getinput=="yes")
{
cout << "Great, Lets keep working!" << endl;
//End of If statement
}
system("PAUSE");
//End of Protype Switch Statement
}
//End of while loop
}
//End of Proinfo()
}
Change year[256] to string year;
Change cin >> year; to getline(cin, year);
Add the line cin.ignore(); before the getline.
Your main problem is that the stream operator >> leaves the newline in the stream so when you try to use getline it reads an empty line. ignore() will chew up the newline and let you read the string you expect.
So this should get you on your way.
cin.ignore();
cout << "Please Enter the Years this molding fits" << endl;
getline(cin, year);
You have some other small problems but you'll figure them out. The worst is forgetting to terminate the loop.
if(getinput=="yes")
{
cout << "Great, Lets keep working!" << endl;
//End of If statement
}
else
{
loop = 0;
continue;
}