My program will loop regardless of whatever char I enter - c++

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.

Related

I am only getting the last input from test() when I run the getStatistics() function

My C++ program wants the user to choose a test option. Option A wants the user to login their id, then they will proceed to take the test. Option B gives the user the results of the taken test. Finally, Option C will make the user quit.
I am trying to get the function getStatistics() to display whether the question that what the user answered is right or wrong, display the user answers and the correct answer.
`
#include <iostream>
#include <string>
# include <cctype>
using namespace std;
const int SIZE = 8;
int totalRightScore{};
int result = totalRightScore;
char ch;
char answer[SIZE] = { 'a', 'b', 'c', 'd' , 'A' , 'B' , 'C' , 'D' };
void test() {
char choice;
cout << "1. What is the capital of USA?" << endl;
cout << "(a)Georgia" << endl;
cout << "(b)Washington, Dc" << endl;
cout << "(c)Berlin" << endl;
cout << "(d)New York City" << endl;
cin >> ch;
if (ch == answer[1] || ch == answer[5]) {
totalRightScore = totalRightScore + 1;
}
cout << "2. How many stars has the USA flag have" << endl;
cout << "(a)50" << endl;
cout << "(b)60" << endl;
cout << "(c)35" << endl;
cout << "(d)13" << endl;
cin >> ch;
if (ch == answer[0] || ch == answer[4]) {
totalRightScore = totalRightScore + 1;
}
cout << "3. What is the name of your SQL instructor?" << endl;
cout << "(a)Alan Anderson" << endl;
cout << "(b)Dr House " << endl;
cout << "(c)Bill Nye" << endl;
cout << "(d)Dr Gill" << endl;
cin >> ch;
if (ch == answer[0] || ch == answer[4]) {
totalRightScore = totalRightScore + 1;
}
}
void loginid() {
string login = "test123";
cout << "enter your login id" << endl; ;
cin >> login;
if (login == "test123") {
test();
}
else
{
cout << "Sorry wrong user ID";
}
}
void getStatistics() {
cout << " Question 1 ";
if (ch == answer[1] || ch == answer[5]) {
cout << "correct" << endl;
cout << "your answer is " << endl;
cout << ch << endl;
cout << "correct answer is " << endl;
cout << "(b) Washington, Dc" << endl;
}
else
{
cout << "incorrect" << endl;
cout << "your answer is " << endl;
cout << ch << endl;
cout << "correct answer is " << endl;
cout << "(b)Washington, Dc" << endl;
}
cout << " Question 2 ";
if (ch == answer[0] || ch == answer[4]) {
cout << "correct" << endl;
cout << "your answer is " << endl;
cout << ch << endl;
cout << "correct answer is " << endl;
cout << "(a) 50" << endl;
}
else
{
cout << "incorrect" << endl;
cout << "your answer is " << endl;
cout << ch << endl;
cout << "correct answer is " << endl;
cout << "(a) 50" << endl;
}
cout << " Question 3 ";
if (ch == answer[0] || ch == answer[4]) {
cout << "correct" << endl;
cout << "your answer is " << endl;
cout << ch << endl;
cout << "correct answer is " << endl;
cout << "(a)Alan Anderson" << endl;
}
else
{
cout << "incorrect" << endl;
cout << "your answer is " << endl;
cout << ch << endl;
cout << "correct answer is " << endl;
cout << "(a)Alan Anderson" << endl;
}
result = totalRightScore;
cout << "your total score is " << result << "/3 " << endl;
totalRightScore = 0;
}
void exit() {
char choice;
cout << "Press Q or q to exit program." << endl;
cin >> choice;
if (choice == 'Q'|| choice == 'q')
{
cout << "Good bye Now" << endl;
}
}
void menu() {
string keepgoing = "y";
char choice;
while (keepgoing == "y")
{
cout << " Select Your Option:\n ";
cout << "(a Login with your userID\n ";
cout << "(b Statistics\n ";
cout << "(c Quit\n ";
cin >> choice;
switch (choice)
{
case 'a':
loginid();
break;
case 'b':
getStatistics();
break;
case 'c':
exit();
break;
}
cout << "would you like to continue? type 'y' to continue " << endl;
cin >> keepgoing;
}
}
`
The problem is that getStatistics() is just getting the last input from test(), for example if you input the right answer for question 1 and input the right answer question 3, when you run the getStatistics()it only remembers the last input from test() and thus deem the right answer for question 1 incorrect. Is there anyway for the getStatistics() to remember all the user answers for all the questions from test(), instead of just getting what is last answered.Thank you.

Why will my program not re-enter my 2nd while loop? C++ [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
All of my commands and alters to the array work individually. However, when i try to return to the menu the screen just starts jittering and will not continue. I am forced to close the program. How do i fix this.
/* Programmer: Joshua Zuber
Program Desc: This Program will allow the user to select an icon to display around an array message!
Program Name: Array Demonstration
Clean Compile Date:
*/
#include<iostream>
#include<string>
#include<iomanip>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
// Arrays
string Masterfile[] = "I want to thank all the C++ students who has helped me this semester. You have inspired me to work harder and to be able to design small C++ programs using a gamming approach. ";
string Studentfile[]= "";
// Variables
int Icon;
char again = 'y';
int i;
int j;
int menu = 'y';
int menu2 = 'n';
int menu3 = 'n';
int menu4 = 'n';
int menu5 = 'n';
int objEdit;
while (toupper(again) == 'Y') // Start Main Loop
{
cout << "Welcome to Array Demonstration!" << "\n\n";
cout << Masterfile[0] << "\n\n";
while(toupper(menu) == 'Y' || toupper(menu2) == 'Y' || toupper(menu3) == 'Y' || toupper(menu4) == 'Y' || toupper(menu5) == 'Y' ) // Start Array Menu Loop
{
cout << "Please select one of the below options to edit this string!" << "\n\n";
Studentfile[0] = Masterfile[0];
cout << "1. Size" << "\n\n";
cout << "2. Replace {all of the C++ students} with {My instructer, Professor Penn}" << "\n\n";
cout << "3. Swap the word {small} with {efficient}" << "\n\n";
cout << "4. Erase the phrase {using a gamming approach}" << "\n\n";
cout << "5. View Final Product" << "\n\n";
cin >> objEdit;
if(objEdit == 1) // Menu Array Size Check
{
cout << "The size of the original string is: " << Masterfile[0].size() << "\n\n";
cout << "\n\n" << "Would you like to return to menu? Y/N " << "\n\n";
cin >> menu2 ;
system("cls");
}
else if(objEdit == 2) // Menu 2nd Option
{
cout << "Changing the phrases!" << "\n\n";
Studentfile[0].replace(16,20,"My instructer, Professor Penn");
cout << Studentfile[0] << "\n\n";
cout << "\n\n" << "Would you like to return to menu? Y/N " << "\n\n";
cin >> menu3;
system("cls");
}
else if(objEdit == 3) // Menu 3rd Option
{
cout << "Changing the phrases!" << "\n\n";
Studentfile[0].replace(131,5,"efficient" );
cout << Studentfile[0] << "\n\n";
cout << "\n\n" << "Would you like to return to menu? Y/N " << "\n\n";
cin >> menu4;
system("cls");
}
else if(objEdit == 4) // Menu 3rd Option
{
cout << "Changing the phrases!" << "\n\n";
Studentfile[0].erase(150);
cout << Studentfile[0] << "\n\n";
cout << "\n\n" << "Would you like to return to menu? Y/N " << "\n\n";
cin >> menu5;
system("cls");
}
else if (objEdit <=0 || objEdit >=6) // Menu Failsafe
{
cout << "Please Select a Valid Number" << "\n\n";
cout << "1. Size" << "\n\n";
cout << "2. Replace {all of the C++ students} with {My instructer, Professor Penn}" << "\n\n";
cout << "3. Swap the word {small} with {efficient}" << "\n\n";
cout << "4. Erase the phrase {using a gamming approach}" << "\n\n";
cout << "5. View Final Product" << "\n\n";
cin >> objEdit;
}
else if(objEdit == 5 || toupper(menu) == 'N') // Menu 5th Option
{
cout << "Please Select one of the following numbers to choose a symbol!" << "\n\n";
cout << "1. *" << "\n\n";
cout << "2. ^" << "\n\n";
cout << "3. #" << "\n\n";
cout << "4. +" << "\n\n";
cin >> Icon;
system("cls");
if(Icon <= 0, Icon >= 5) // User Failsafe
{
cout << "You're Entry Is Not Valid" << "\n\n";
cout << "Please Select one of the following numbers to choose a symbol!" << "\n\n";
cout << "1. *" << "\n\n";
cout << "2. ^" << "\n\n";
cout << "3. #" << "\n\n";
cout << "4. +" << "\n\n";
cin >> Icon;
system("cls");
}
else // Icon Breakdown
{
if(Icon == 1) // Icon Choice 1
{
for (i=1;i<=1;i++)
{
for (j=1;j<=i;j++);
{
cout << "*******************************************************************************" << "\n";
cout << Studentfile[0] << "\n";
cout << "*******************************************************************************" << "\n";
cout << endl;
cout << "\n\n" << "Do you wish to play again? Y/N " << "\n\n";
cin >> again;
system("cls");
}
}
}
else if(Icon == 2) // Icon Choice 2
{
for (i=1;i<=1;i++)
{
for (j=1;j<=i;j++);
{
cout << "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" << "\n";
cout << Studentfile[0] << "\n";
cout << "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" << "\n";
cout << endl;
cout << "\n\n" << "Do you wish to play again? Y/N " << "\n\n";
cin >> again;
system("cls");
}
}
}
else if(Icon == 3) // Icon Choice 3
{
for (i=1;i<=1;i++)
{
for (j=1;j<=i;j++);
{
cout << "###############################################################################" << "\n";
cout << Studentfile[0] << "\n";
cout << "###############################################################################" << "\n";
cout << endl;
cout << "\n\n" << "Do you wish to play again? Y/N " << "\n\n";
cin >> again;
system("cls");
}
}
}
else if(Icon == 4) // Icon Choice 4
{
for (i=1;i<=1;i++)
{
for (j=1;j<=i;j++);
{
cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << "\n";
cout << Studentfile[0] << "\n";
cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << "\n";
cout << endl;
cout << "\n\n" << "Do you wish to play again? Y/N " << "\n\n";
cin >> again;
system("cls");
}
}
}
else // Icon Choice 5
{
cout << "Sorry You Didn't Want to Play" << "\n\n";
cout << "\n\n" << "Do you wish to play again? Y/N " << "\n\n";
cin >> again;
system("cls");
}
}
}
} // End Menu Loop
} // End Main Loop
cout << "Thank you for playing!" << "\n\n";
system("pause");
return 0;
}
Probably because you define menu .. menu5 as int. Try:
char menu = 'y';
char menu2 = 'n';
char menu3 = 'n';
char menu4 = 'n';
char menu5 = 'n';
....

C++ Do while loop condition not working

#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int main(){
int gnumber, rnumber;
char choice;
int tries;
do {
cout << "Welcome to the Number Guessing Game!" << endl;
cout << endl; // breakline
cout << "How many tries: ";
cin >> tries;
cout << endl;
while (tries > 0){
srand(time(NULL));
rnumber = rand() % 99;
cout <<"Enter an integer greater than or equal to 0 and less than 100:";
cin >> gnumber;
system("cls");
if (tries != 1){
if (gnumber < 100 && gnumber >= 0){
if (gnumber == rnumber){
cout << "Congratulations! You've guessed the number." << endl;
tries--;
cout << "Remaining tries: " << tries << endl;
}
else if (gnumber > rnumber){
cout << "Your guess is higher than the number." << endl;
tries--;
cout << " Guess Again!" << endl;
cout << "Remaining tries: " << tries << endl;
}
else{
cout << "Your guess is lower than the number." << endl;
tries--;
cout << " Guess Again!" << endl;
cout << "Remaining tries: " << tries << endl;
}
}
else
cout << "Must greater or equal to 0 and lesser than 100!" << endl;
}
else
{
cout << "Game over!" <<" The number is: " << rnumber << endl;
cout << "Play Again? (Y/N)" << endl;
cin >> choice;
system("cls");
}
}
}while(choice == 'Y' || choice == 'y'); //
system("pause");
return 0;
}
EVEN IF I ENTER CHOICE AS 'N' OR 'n' IT WONT STOP THE LOOP.
And even if I enter 'Y' or 'y', it does not ask how many tries i wanted.
Instead it just asks directly what integer I would want to enter.
Please try to copy and compile the code to further understand what the problem is. Please help.
P.S.: This is a guessing program I'm making by the way...
the bug in your inner loop if the use enters a value other than one in else you don't decrement tries so it gets stuck:
else
{
cout << "Game over!" <<" The number is: " << rnumber << endl;
cout << "Play Again? (Y/N)" << endl;
cin >> choice;
system("cls");
tries--; // add this
}

Infinite loop in my program

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).

Serendipity booksellers software program C++

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;