Ok, so for my school project we are basically making a menu with 20 max people to enter information and change if need be. Everything was working fine. However, our assignment has us check input for zip code and Account Balance for integer values. I used a do-while loop for ZipCode validation until a positive number and a digit was entered. However, I get an infinite loop that I can't seem to fix. Here is my code. The error lies on lines 57-68 if you put into a compiler. Every time I enter a letter instead of a integer, I get an infinite loop. But I can't figure out why. Thanks!
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
using namespace std;
struct Account //Structure to be used throughout
{
string CustomerName;
string CustomerAddress;
string City;
string State;
int ZIPCode;
string Telephone;
int AccountBalance;
string DateOfLastPayment;
};
//function prototypes
void valueChangeFunc(string, Account[], int);//This function will be used in option 2 for editing a certain customer information
int main()
{
Account array[20]; //Array to hold up to 20 customers
int choice; //this will hold which option the user decides to make 1-4
bool flagZip = false; //This will be used later on as a flag for a do-while loop
bool flag = false; //This will be used as a flag for the do-while loop right now
int index = 0; //Index for our customers. This tells how many customers have been entered
do //This do while loop will continue to ask the user what option to do until array fills up with 20 people and 4 is not entered
{
cout << "1. Enter new account information \n" <<endl
<< "2. Change account information \n" << endl
<< "3. Display all account information\n" <<endl
<< "4. Exit the program \n" <<endl;
cin >> choice;
if (choice > 4 || choice <= 0)//If user enters a number bigger than 4 or less then or equal to 0. Error!
cout << "Please enter a number between 1 and 4" << endl;
else if(choice == 1)
{
cout << "CustomerName: ";
cin.ignore();
getline(cin, array[index].CustomerName);
cout << "CustomerAddress ";
getline(cin, array[index].CustomerAddress);
cout << "City: ";
getline(cin, array[index].City);
cout << "State: ";
getline(cin, array[index].State);
do
{
cout << "Zip Code: ";
cin >> array[index].ZIPCode;
cin.ignore();
if (!isdigit(array[index].ZIPCode) && array[index].ZIPCode <= 0)
cout << "Please enter a valid entry " << endl;
else
flagZip = true;
}while(flagZip == false);
cout << "Telephone: ";
getline(cin, array[index].Telephone);
flagZip = false;
do
{
cout << "AccountBalance: ";
cin >> array[index].AccountBalance;
cin.ignore();
if (array[index].AccountBalance <= 0)
cout << "Please enter a valid entry " << endl;
else
flagZip = true;
}while(flagZip == false);
cout << "DateOfLastPayment: ";
getline(cin, array[index].DateOfLastPayment);
cout << "\n\nCustomerName: " << array[index].CustomerName << endl;
cout << "CustomerAddress " << array[index].CustomerAddress <<endl;
cout << "City: " << array[index].City << endl;
cout << "State: " << array[index].State << endl;
cout << "Zip Code: " << array[index].ZIPCode << endl;
cout << "Telephone: " << array[index].Telephone <<endl;
cout << "AccountBalance: " << array[index].AccountBalance << endl;
cout << "DateOfLastPayment: " << array[index].DateOfLastPayment << endl;
cout << "You have entered information for customer number " << index << endl << endl;
index++;
}
else if(choice == 2 && index != 0)
{
int num;
string valueChange;
do
{
cout << " Customer number: ";
cin >> num;
if (num > (index-1) || num < 0)
cout << " There is no customer with that number " << endl;
}while (num > (index-1));
cout << "\n\nCustomer Name: " << array[num].CustomerName << endl;
cout << "Customer Address " << array[num].CustomerAddress <<endl;
cout << "City: " << array[num].City << endl;
cout << "State: " << array[num].State << endl;
cout << "ZIPCode: " << array[num].ZIPCode << endl;
cout << "Telephone: " << array[num].Telephone <<endl;
cout << "Account Balance: " << array[num].AccountBalance << endl;
cout << "Date of last payment: " << array[num].DateOfLastPayment << endl;
cout << "You have requested information for customer number " << num << endl << endl;
cout << "What value do you want to change? (press 4 to change 'Date of last payment') \n";
cin.ignore();
getline(cin,valueChange);
valueChangeFunc(valueChange, array, num);
cout << "\nHere is the new value you entered for " << valueChange << endl;
cout << "\n\nCustomer Name: " << array[num].CustomerName << endl;
cout << "Customer Address " << array[num].CustomerAddress <<endl;
cout << "City: " << array[num].City << endl;
cout << "State: " << array[num].State << endl;
cout << "ZIPCode: " << array[num].ZIPCode << endl;
cout << "Telephone: " << array[num].Telephone <<endl;
cout << "Account Balance: " << array[num].AccountBalance << endl;
cout << "Date of last payment: " << array[num].DateOfLastPayment << endl << endl;
}
else if(choice == 3 && index != 0)
{
int num2;
do
{
cout << "Enter the Customer Number to display information regarding that customer" << endl;
cin >> num2;
if (num2 > (index-1) || num2 < 0)
cout << "That Customer does not exist " <<endl;
}
while(num2 > (index-1));
cout << "\n\nCustomerName: " << array[num2].CustomerName << endl;
cout << "CustomerAddress " << array[num2].CustomerAddress <<endl;
cout << "City: " << array[num2].City << endl;
cout << "State: " << array[num2].State << endl;
cout << "Zip Code: " << array[num2].ZIPCode << endl;
cout << "Telephone: " << array[num2].Telephone <<endl;
cout << "AccountBalance: " << array[num2].AccountBalance << endl;
cout << "DateOfLastPayment: " << array[num2].DateOfLastPayment << endl;
cout << "You have entered information for customer number " << index << endl << endl;
}
else
flag = true;
}while (flag == false);
return 0;
}
void valueChangeFunc(string valueChange2, Account array[], int num)
{
if (valueChange2 == "Customer Name" || valueChange2 == "Customer name" || valueChange2 == "customer Name" || valueChange2 == "customer name")
{
cout << "\nEnter new value for Customer Name: " <<endl;
getline(cin, array[num].CustomerName);
}
if (valueChange2 == "Customer Address" || valueChange2 == "Customer address" || valueChange2 == "customer Address" || valueChange2 == "customer address")
{
cout << "\nEnter new value for Customer Address: " <<endl;
getline(cin, array[num].CustomerAddress);
}
else if(valueChange2 == "city" || valueChange2 == "City")
{
cout << "\nEnter new value for City: " << endl;
getline(cin, array[num].City);
}
else if(valueChange2 == "state" || valueChange2 == "State")
{
cout << "Enter a value for State: " << endl;
getline(cin,array[num].State);
}
else if(valueChange2 == "Zip Code" || valueChange2 == "zip Code" || valueChange2 == "Zip code" || valueChange2 == "zip code")
{
cout << "\nEnter a value for Zip Code: " << endl;
cin >> array[num].ZIPCode;
}
else if(valueChange2 == "telephone" || valueChange2 == "Telephone")
{
cout << "\nEnter a value for Telephone: " << endl;
getline(cin, array[num].Telephone);
}
else if(valueChange2 == "Account Balance" || valueChange2 == "Account balance" || valueChange2 == "account Balance" || valueChange2 == "account balance")
{
cout << "\nEnter a value for account balance: " << endl;
cin >> array[num].AccountBalance;
}
else if(valueChange2 == "4")
{
cout << "\nEnter the value for Date of last payment: " << endl;
getline(cin, array[num].DateOfLastPayment);
}
else
cout << "Not entered correctly. Please enter a valid entry to edit " << endl;
}
Again everything worked until I started to use a loop to check for digit value of ZipCode. The loop only goes infinite when I enter a letter. It works for a negative number and positive number.
Short answer can be found in cplusplus.com (read the third paragraph)
Long answer:
This error isn't about ZipCode only, you can generate the same error when you input a letter instead of a number at the very first cin call.
cin is not type-safe so using a wrong type as an input results in an undefined behaviour (like the infinite loop you were experiencing) and that is why cin is a bit prone to errors. Also, cin gets the input value, however it doesn't remove newline, reading to a bit dirtier input from what you'd get with other methods.
Speaking of other methods, as explained in the link, try to use getline() whenever it is possible. You can use that function to get what cin buffer contains as a string and do additional type-check if necessary. Bug-free programs are more important than shorter programs.
As a personal note: try to use while loops instead of do..while ones when you can. That is not a general rule of programming but it looks more readable and is easier to understand in general (IMHO).
Also, try to use functions to split your program into parts. For example, the cout blocks where you are just printing the information stored to the screen can be turned into a function. You're using the same cout structure (it would shorten your code by 4 * 9 lines).
Finally, if you're using an integer as a key value to separate algorithms, try to use switch...case instead of if-else blocks. (Again, just my opinion).
Related
I have written this code using array of structures in C++ and the output was correct, but when I included the pointers, the output is not correct and missing a lot of, what is the reason of this?
This is the code using pointers:
#include <iostream>
using namespace std;
struct Course {
string CourseCode;
string CourseName;
string LecturerName;
};
struct Student {
string StudentID;
string StudentName;
string Nickname;
Course info;
};
void menu(void) {
cout << "=================================" << endl;
cout << " MENU " << endl;
cout << "=================================" << endl;
cout << " 1- Add new students" << endl;
cout << " 2- Display student list" << endl;
cout << " 3- Add new course" << endl;
cout << " 4- Display Course Offered" << endl;
cout << " 5- Exit Program" << endl;
cout << "=================================" << endl << endl;
}
int main()
{
Student *ptr[2] ;
Student details[2];
ptr[2] = &details[2];
int m, option, courNo;
menu();
cout << "Choose an option from the menu: ";
cin >> option;
while (option != 5)
{
if (option == 1) {
// cout << "\nHow many students do you want to enter? ";
// cin >> stuNo;
for (m = 0; m < 2; m++) {
cout << "\nEnter student " << m + 1 << " details: " << endl;
cout << "ID: ";
cin >> ptr[m]->StudentID;
cout << "Name: ";
cin >> ptr[m]->StudentName;
cout << "Nickname: ";
cin >> ptr[m]->Nickname;
}
}
else if (option == 2) {
cout << "\nThe students details you entered are:" << endl;
for (m = 0; m < 2; m++) {
cout << "\nStudent " << m + 1 << ": " << endl;
cout << "ID: " << ptr[m]->StudentID << endl;
cout << "Name: " << ptr[m]->StudentName << endl;
cout << "Nickname: " << ptr[m]->Nickname << endl;
}
}
else if (option == 3) {
cout << "\nHow many courses do you want to enter? ";
cin >> courNo;
for (m = 0; m < courNo; m++) {
cout << "\nEnter course " << m + 1 << " details: " << endl;
cout << "Course Code: ";
cin >> ptr[m]->info.CourseCode;
cout << "Course Name: ";
cin >> ptr[m]->info.CourseName;
cout << "Lecturer Name: ";
cin >> ptr[m]->info.LecturerName;
}
}
else if (option == 4) {
cout << "\nThe courses details you entered are:" << endl;
for (m = 0; m < 2; m++) {
cout << "\nCourse " << m + 1 << ": " << endl;
cout << "Course Code: " << ptr[m]->info.CourseCode << endl;
cout << "Course Name: " << ptr[m]->info.CourseName << endl;
cout << "Lecturer Name: " << ptr[m]->info.LecturerName << endl;
}
}
else
cout << "Invalid number! Please re-enter a choice from the menu." << endl;
cout << "=====================================================" << endl;
cout << "\nChoose an option from the menu: ";
cin >> option;
}
if (option == 5)
cout << "End of program!" << endl;
}
This is the output of the program, after I enter the code it was terminated:
=================================
MENU
=================================
1- Add new students
2- Display student list
3- Add new course
4- Display Course Offered
5- Exit Program
=================================
Choose an option from the menu: 3
How many courses do you want to enter? 2
Enter course 1 details:
Course Code: 123
This is the output without using pointers, it was like this which is the output that I'm looking for:
=================================
MENU
=================================
1- Add new students
2- Display student list
3- Add new course
4- Display Course Offered
5- Exit Program
=================================
Choose an option from the menu: 3
How many courses do you want to enter? 2
Enter course 1 details:
Course Code: 0000
Course Name: course1
Lecturer Name: lecturer1
Enter course 2 details:
Course Code: 1111
Course Name: course2
Lecturer Name: lecturer2
=====================================================
Choose an option from the menu: 5
End of program!
I need to create arrays that save the quantity of the item the user selects and also prints out a receipt with the product, quantity and the total price. Please help me understand how to do this. I've got a basic understanding of what an array is. I just couldn't figure out how to save the users input.
#include <iostream>
#include <Windows.h>
#include <cstdlib>
#include <string>
#include "customerclass.h"
using namespace std;
//***** Functions to calculate the price of multiple items *****
void finalPrice1(int itemQuantity) {
float price;
price = itemQuantity * 3.00;
cout << "Your total is $" << price << endl;
cout << "Thank you for using my shop" << endl;
exit(0);
}
void finalPrice2(int itemQuantity) {
float price;
price = itemQuantity * 2.50;
cout << "Your total is $" << price << endl;
cout << "Thank you for using my shop" << endl;
exit(0);
}
void finalPrice3(int itemQuantity) {
float price;
price = itemQuantity * 1.25;
cout << "Your total is $" << price << endl;
cout << "Thank you for using my shop" << endl;
exit(0);
} //***** End of functions that calculate price of multiple items *****
int main(void)
{
char selection = ' ';
string lname = "";
string luserAddress;
int itemQuantity;
string orderFinalized;
CustomerInfo myCustomerInfo;
do
{ // Displaying menu
cout << "Hello, welcome to my online shop! What is your name? " << endl;
cin >> lname;
cout << " And what is your shipping address? " << endl;
cin >> luserAddress;
myCustomerInfo.setName(lname);
myCustomerInfo.setAddress(luserAddress);
cout << lname + ", nice to meet you. Here are the items in my shop followed by the price, please enter the number that corresponds to the item you want. \n " << endl;
cout << "Products \n";
cout << "1 - Chocolate candy bar - $3.00" << endl;
cout << "2 - Sour hard candy - $2.50" << endl;
cout << "3 - Mints - $1.25" << endl;
cout << "4 - Exit" << endl << endl;
cout << "Enter selection ";
// Reading User Selection
cin >> selection;
switch (selection)
{
case '1':
cout << "You've chosen a Chocolate candy bar. How many would you like? ";
cin >> itemQuantity;
cout << "Ok, will this finalize your order? Type and enter either 'Yes' or 'No' " << endl;
cin >> orderFinalized;
if (orderFinalized == "Yes" || orderFinalized == "yes" || orderFinalized == "YES") {
cout << myCustomerInfo.getName() + " your items will be shipped to " << myCustomerInfo.getAddress() << endl;
cout << "Printing your receipt now..." << endl;
finalPrice1(itemQuantity);
}
break;
case '2':
cout << "You've chosen Sour hard candy. How many would you like? ";
cin >> itemQuantity;
cout << "Ok, will this finalize your order? Type and enter either 'Yes' or 'No' " << endl;
cin >> orderFinalized;
if (orderFinalized == "Yes" || orderFinalized == "yes" || orderFinalized == "YES") {
cout << myCustomerInfo.getName() + " your items will be shipped to " << myCustomerInfo.getAddress() << endl;
cout << "Printing your receipt now..." << endl;
finalPrice2(itemQuantity);
}
break;
case '3':
cout << "You've chosen Mints. How many would you like? ";
cin >> itemQuantity;
cout << "Ok, will this finalize your order? Type and enter either 'Yes' or 'No' " << endl;
cin >> orderFinalized;
if (orderFinalized == "Yes" || "yes" || "YES") {
cout << myCustomerInfo.getName() + " your items will be shipped to " << myCustomerInfo.getAddress() << endl;
cout << "Printing your receipt now..." << endl;
finalPrice3(itemQuantity);
}
break;
case '4':
cout << "Thank you for using my shop. <exiting now...>" << endl;
break;
default: cout << "Invalid selection. Please try again";
}
cout << endl << endl;
} while (selection != '4');
return 0;
}
You need dynamic array. For example:
cin >> itemQuantity;
// create a array during runtime
// and the size is itemQuantity
// you can access the ith array element by items[i]
Item *items= new Item[itemQuantity];
Or you can use the vector,
vector<Item> items;//you can also access the ith element by items[i]
items.push_back(hard_candy);//items = {hard_candy}
items.push_back(soft_candy);//items = {hard_candy, soft_candy}
items.pop_back();//items = {hard_candy}
BTW, the case 3 in your code has some error:
orderFinalized == "Yes" || "yes" || "YES"//wrong
orderFinalized == "Yes" || orderFinalized == "yes" || orderFinalized == "YES"//right
Why is my else, cout << "You have entered an incorrect code" still executing and writing to the screen after I enter r or R and complete the calculation and dialogue. The same does not happen when I enter p or P and follow through with that portion of my program. Sorry for the incredibly nooby question.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char service;
int number;
int minutes;
int dayMinutes;
int nightMinutes;
double bill;
double dayCharge;
double nightCharge;
double const REG_FEE = 10.00;
double const PREM_FEE = 25.00;
double const REG_MIN = 0.20;
double const PREM_DAY = 0.10;
double const PREM_NIGHT = 0.05;
cout << "Please enter your account number: ";
cin >> number;
cout << "Please enter your service type (regular or premium): ";
cin >> service;
if (service == 'r' || service == 'R')
{
cout << "How many minutes have been used for this service?: ";
cin >> minutes;
if (minutes <= 50)
{
bill = REG_FEE;
cout << fixed << showpoint << setprecision(2);
cout << "Your bill is $" << bill << "." << endl;
cout << "The account number entered was: " << number << "." << endl;
cout << "The service type entered was: " << service << "." << endl;
cout << "You used: " << minutes << " minutes." << endl;
}
else
{
bill = ((minutes - 50) * REG_MIN) + REG_FEE;
cout << fixed << showpoint << setprecision(2);
cout << "Your bill is $" << bill << "." << endl;
cout << "The account number entered was: " << number << "." << endl;
cout << "The service type entered was: " << service << "." << endl;
cout << "You used: " << minutes << " minutes." << endl;
}
}
if (service == 'p' || service == 'P')
{
cout << "How many minutes were used during the day?: ";
cin >> dayMinutes;
cout << "How many minutes were used during the night?: ";
cin >> nightMinutes;
if (dayMinutes > 75)
{
dayCharge = ((dayMinutes - 75) * PREM_DAY);
}
if (nightMinutes > 100)
{
nightCharge = ((nightMinutes - 100) * PREM_NIGHT);
}
bill = dayCharge + nightCharge + PREM_FEE;
cout << fixed << showpoint << setprecision(2);
cout << "Your bill is $" << bill << "." << endl;
cout << "The account number entered was: " << number << "." << endl;
cout << "The service type entered was: " << service << "." << endl;
cout << "You used: " << dayMinutes + nightMinutes << " minutes." << endl;
}
else
{
cout << "You have entered an invalid service code." << endl;
cout << "The account number entered was: " << number << "." << endl;
cout << "The service type entered was: " << service << "." << endl;
}
return 0;
}
That's because you need this-
if (service == 'r' || service == 'R'){
// your code
}
else if(service == 'p' || service == 'P'){
//your code
}
else {
//your code
}
Problem right now with your code is that if you even enter 'r' or 'R', due to if else condition with 'p' or 'P' becomes false and else part gets executed .
That's why you needed to use if - else if format so that for an input only one part is executed.
I have been working on a very very basic calculation program in C++. It calculates the square root of a number, and also squares it if the user wants. This is what I have so far (I know it's probably rubbish code, but I'm a beginner just experimenting to see how it all works. Any suggestions greatly appreciated though):
#include <iostream>
#include <stdlib.h>
#include <math.h>
using namespace std;
int number; // Global variables to be used in void functions as well as main.
int squaredNumber;
double sqrtResult;
char input;
char useAgain;
void squareNum(); // Prototypes for the void functions
void sqrtNum();
void useAgainQuery();
int main()
{
retry: // Establishing somewhere to send user if their input is invalid.
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Do you want to square a number or find the square root of a number?" << endl;
cout << "Please select 1 or 2 respectively." << endl;
cout << endl;
cin >> input;
if (input == '1')
{
cout << "Please press ENTER to continue." << endl;
cin.ignore().get();
squareNum(); // If the input is 1, run the void to square a number.
}
else if (input == '2')
{
cout << "Please press ENTER to continue." << endl;
cin.ignore().get();
sqrtNum(); // If the input is 2, run the void to sqrt a number.
}
else if (input != '1' || '2')
{
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Your selection was invalid, please enter 1 or 2." << endl;
cin.ignore().get();
goto retry; // If the input isn't either 1 or 2, send back to the start of program.
}
return 0;
}
void squareNum() // function to square the inputted number.
{
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Enter the number you want to square." << endl;
cin >> number;
cout << "You have chosen: " << number << endl;
cout << "Press ENTER to calculate." << endl;
cin.ignore().get();
system("cls");
squaredNumber = number * number; // Simple maths to find the square number
cout << "You have squared " << number << "." << endl;
cout << "The result was " << squaredNumber << "." << endl;
cout << "Press ENTER to continue." << endl;
cin.get();
useAgainQuery();
return;
}
void sqrtNum()
{
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Enter the number you would like the square root of." << endl;
cin >> number;
cout << "You have chosen: " << number << "." << endl;
cout << "Press ENTER to calculate." << endl;
cin.ignore().get();
system("cls");
sqrtResult = sqrt(number);
cout << "You have found the square root of " << number << "." << endl;
cout << "The result was: " << sqrtResult << "." << endl;
cout << "Press ENTER to continue." << endl;
cin.get();
useAgainQuery();
return;
}
void useAgainQuery()
{
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Would you like to make another calculation?" << endl;
cout << "Y for Yes and N for No." << endl;
cout << endl;
cin >> useAgain;
if (useAgain == 'Y' || 'y')
{
retry2: // Establishing somewhere to send user if their input is invalid.
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Do you want to square a number or find the square root of a number?" << endl;
cout << "Please select 1 or 2 respectively." << endl;
cout << endl;
cin >> input;
if (input == '1')
{
cout << "Please press ENTER to continue." << endl;
cin.ignore().get();
squareNum(); // If the input is 1, run the void to square a number.
}
else if (input == '2')
{
cout << "Please press ENTER to continue." << endl;
cin.ignore().get();
sqrtNum(); // If the input is 2, run the void to sqrt a number.
}
else if (input != '1' || '2')
{
system("cls");
cout << "Square Calcualtions" << endl;
cout << "******************" << endl;
cout << endl;
cout << "Your selection was invalid, please enter 1 or 2." << endl;
cin.ignore().get();
goto retry2;
}
}
else if (useAgain != 'Y' || 'y')
return;
return;
}
So yeah, when I go through and it asks "Would you like to play again", it goes through it over and over. It doesn't matter what key I press but it loops. Any help would be greatly appreciated!
Change your condition here:
if (useAgain == 'Y' || 'y')
to
if (useAgain == 'Y' || useAgain=='y')
Also, change this:
else if (useAgain != 'Y' || 'y')
{
return;
}
to this:
else if (useAgain != 'Y' && useAgain!='y')
{
return;
}
Perhaps try creating a bool variable that controls the entire main loop, like this:
#include <InsertLibrariesHere>
int main(){
bool running=true;
while(running){
//calculations here
//continue(Y/N)?
if (input == N || input == n){running = false;}
}
}
Don't use goto, use a while(1) instead.
your last if statement is wrong, it needs to be
if (input != '1' && input != '2')
You can simplify your comparisons to letters:
if (std::toupper(useAgain) == 'Y')
or
if (std::tolower(useAgain) == 'y')
You can also convert the case after you input:
cin >> useAgain;
useAgain = std::toupper(useAgain);
if (useAgain == 'Y')
There is also std::transform is you need to transform a std::string to all lower or all upper case.
this is a project I'm working on which comes from the book I'm using to learn C++ - "Starting out with C++". I'm having a problem with the cashier portion of the project at the moment. It asks the user to enter the date, quantity, isbn, title, and price of the book. Then, it asks the user if they wish to enter another book. Regardless of whether they type "y" or "n" it continues to the next part of the program. I don't really know why the for loop doesn't repeat after I type "y" to enter another book. Also, the date is coming out with garbage at the end when it is displayed, that's another thing I need to fix. Any help would be appreciated. There is definitely more problems but the main problem is in the cashier function in the first for loop. I didn't include the whole program because it's very long.
/*
* mainmenu.cpp
* Serendipity Booksellers software
*
* Created by Abraham Quilca on 9/5/12.
* Copyright 2012 __MyCompanyName__. All rights reserved.
*
*/
#include<iostream>
#include<iomanip>
#include<cstring>
#include"mainmenu.h"
using namespace std;
char bookTitle[20][51],
isbn[20][14],
author[20][31],
publisher[20][31],
dateAdded[20][11];
int qtyOnHand[20];
double wholesale[20];
double retail[20];;
int main()
{
int choice;
do
{
cout << "\t\t Serendipity Booksellers"<< endl;
cout << "\t\t\t Main Menu" << endl << endl;
cout << "\t\t1. Cashier Module" << endl;
cout << "\t\t2. Inventory Database Module" << endl;
cout << "\t\t3. Report Module" << endl;
cout << "\t\t4. Exit" << endl << endl;
cout << "\t\tEnter your choice: ";
cin >> choice;
cout << endl;
switch (choice)
{
case 1:
cashier();
break;
case 2:
invmenu();
break;
case 3:
reports();
break;
case 4:
continue;
break;
default:
cout << "\t\tPlease enter a number in the range 1-4." << endl << endl;
}
}
while(choice != 4);
cout << "\t\tYou selected item 4." << endl;
return 0;
}
// Cashier function
void cashier()
{
char again;
char date[8];
int quantity[20] = {0};
char ISBN[20][20] = {0};
char title[20][40] = {0};
float price[20] = {0}, bookTotal[20] = {0}, subtotal, total, tax;
const float tax_rate = .06;
cout << "Serendipity Booksellers" << endl;
cout << " Cashier Module" << endl << endl;
for(int count = 0; count < 20; count++)
{
cout << "Date: ";
cin >> date;
cout << "Quantity of Book: ";
cin >> quantity[count];
cout << "ISBN: ";
cin >> ISBN[count];
cout << "Title: ";
cin.ignore();
cin.getline(title[count], 40);
cout << "Price: ";
cin >> price[count];
bookTotal[count] = quantity[count] * price[count];
subtotal += price[count];
cout << "Would you like to enter another book? (Y/N) ";
cin >> again;
if(again == 'N' || 'n')
count = 21; // This line will end the for loop
}
// Calculating tax and total
tax = subtotal * tax_rate;
total = subtotal + tax;
cout << "\n\nSerendipity Booksellers" << endl << endl;
cout << "Date:" << date << endl << endl;
cout << "Qty\t ISBN\t\t "
<< left << setw(40) << "Title" << "Price\t Total" << endl
<< "-------------------------------------------------------------------------------"
<< endl << endl;
for(int count = 0; count < 20; count++)
{
cout << quantity[count] << "\t " << ISBN[count] << " " << left << setw(40) << title[count]
<< setprecision(2) << fixed << "$" << setw(6) << price[count] << " $" << setw(6) << bookTotal[count]
<< endl << endl;
}
cout << "\t\t\t Subtotal" << "\t\t\t\t $" << setw(6) << subtotal << endl;
cout << "\t\t\t Tax" << "\t\t\t\t $" << setw(6) << tax<< endl;
cout << "\t\t\t Total" "\t\t\t\t $" << setw(6) << total << endl << endl;
cout << "Thank You for Shopping at Serendipity!" << endl << endl;
}
if(again == 'N' || 'n')
This doesn't do what you think it does. Look at it like this:
if((again == 'N') || ('n'))
Is again == N true OR is n true? Well n will always be true (it is a char with non-zero value) so your loop will always end immediately. What you want is:
if(again == 'N' || again == 'n')
Also, you can break out of a loop using the aptly named break keyword:
if (again == 'N' || again == 'n') {
break;
}
The problem with the loop is this line:
if(again == 'N' || 'n')
C++ doesn't know that you mean it to check again against both characters. Instead, it tries again == 'N', which fails, and then tries 'n', which - not being zero - evaluates as true.
Instead, try:
if (again == 'N' || again == 'n')
break;