Password count help - c++

void getPassword()
{
while (true)
{
string password;
cout << "Enter the password: ";
getline(cin, password);
if (password == "123456") break;
cout << "INVALID. ";
} // while
} // getPassword
int main()
{
getPassword();
double P;
double r;
double N = 360;
double rate;
cout << "What's the mortgage amount? ";
cin >> P;
cin.ignore(1000, 10);
cout << "What's the annual interest rate? ";
cin >> r;
cin.ignore(1000, 10);
rate = r / 100 / 12;
// (p * (1 + r)n * r) / ((1 + r)n - 1)
double M = P * ((pow))(1 + rate, N) * rate / (((pow))(1 + rate, N) -1);
cout.setf(ios::fixed|ios::showpoint);
cout << setprecision(2);
cout << "Principal = $" << P << endl;
cout.unsetf(ios::fixed|ios::showpoint);
cout << setprecision(6); // resets precision to its default
cout << "Interest Rate = " << r << "%" << endl;
cout << "Amortization Period = " << N / 12 << " years" << endl;
cout << "The monthly payment = $" << M << endl;
ofstream fout;
fout.open("mortgages.txt", ios::app);
if (!fout.good()) throw "I/O error";
fout.setf(ios::fixed|ios::showpoint);
fout << setprecision(2);
fout << "Principal = $" << P << endl;
fout.unsetf(ios::fixed|ios::showpoint);
fout << setprecision(6); // resets precision to its default
fout << "Interest Rate = " << r << "%" << endl;
fout << "Amortization Period = " << N / 12 << " years" << endl;
fout << "The monthly payment = $" << M << endl;
fout.close();
return 0;
}
What's up guys? I have a homework assignment for comsc and I have hit a roadblock in my last program. What I am attempting to do is limit the user of this program to 3 invalid password attempts. Do I need to change this to a value-returning subprogram or can I accomplish this without doing so? Any help would be much appreciated!!

Easiest way would be to change getPassword so that it returns a bool that signifies whether the user put in the right password. Then, rather than while (true), say for (int i = 0; i < 3; ++i)...and rather than break, return true. After the loop, return false since they went 3 rounds without putting in the right password.
In the rest of the program, rather than just calling getPassword, check its return value. If it's false, print an error message and exit.
Something like:
bool checkPassword() { // renaming this, since it doesn't just *get* a password
for (int i = 0; i < 3; ++i) {
string password;
std::cout << "Enter password: " << std::flush;
std::getline(std::cin, password);
if (password == "123456") return true;
std::cout << "INVALID.\n";
}
std::cout << "Maximum attempts exceeded.\n";
return false;
}
int main() {
if (!checkPassword()) {
return 1;
}
... rest of main() here ...
}

Related

gotoxy prints wrong in c++

I am making a menu for a store with 4 options; add product, delete product, see table of created products and exit the program.
I finished the option to add products and exit, they both work fine.
Now I have to make the option to see the product table, supposedly I had already finished it but I noticed a problem ...
The first time I go in to see the product table, it prints it to me normally, like this.
enter image description here
But when I go to the menu and go back to the product table, it prints it like this.
enter image description here
Like I said, it only prints it right the first time I see it, then it prints it wrong.
Do you know how I can solve it?
This is the part of the code where I print the product table.
void table()
{
int c = k, m = 7;
system("cls");
cout << endl;
cout << "Table of created products";
cout << endl;
cout << endl;
cout << " number of order ";
cout << "| Name of product |";
cout << " Product code |";
cout << " Amount |";
cout << " Unit price |";
cout << " Subtotal |";
cout << " IVA |";
cout << " total price |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
for (int L = 2; L <= c; L++)
{
cout << " ";
cout << "| |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
}
for (int h = 1; h < c; h++)
{
gotoxy(8, m);
cout << product[h].numor;
gotoxy(20, m);
cout << product[h].descr;
gotoxy(52, m);
cout << product[h].cod;
gotoxy(70, m);
cout << product[h].cant;
gotoxy(83, m);
cout << "$" << product[h].preuni;
gotoxy(96, m);
cout << "$" << product[h].subt;
gotoxy(107, m);
cout << "$" << product[h].IVA;
gotoxy(119, m);
cout << "$" << product[h].total;
m = m + 4;
}
cout << "\n\n\n";
system("pause");
system("cls");
}
This is my complete code (maybe I have one or another library too many because I have been experimenting).
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<string>
#include<ctype.h>
#include <stdio.h>
#include <windows.h>
#include<iomanip>
using namespace std;
struct products
{
int numor{},
cant{};
float preuni{},
subt{},
IVA{},
total{};
string cod{};
string descr{};
}product[51];
void add();
void intro_code();
int val_code(char codigo[]);
void table();
void gotoxy(int x, int y);
int i = 1; //Product No. (counter)
int k = 1; //Consecutive number (counter)
int main()
{
char opc;
cout << " Welcome ";
cout << endl;
cout << "\n1.- Add product.";
cout << "\n2.- Delete product.";
cout << "\n3.- Table of created products.";
cout << "\n4.- Exit";
cout << endl;
cout << "\nWhat do you want to do today?: "; cin >> opc;
switch (opc)
{
case '1':
system("cls");
cout << "\nAdd product";
add();
system("pause");
system("cls");
return main();
case '2':
cout << "\nDelete product";
system("cls");
return main();
case '3':
table();
return main();
case '4':
exit(EXIT_SUCCESS);
default:
system("cls");
cout << "Warning: the data entered is not correct, try again.\n\n";
return main();
}
return 0;
}
void add()
{
int can;
cout << "\nHow many products do you want to register?: "; cin >> can;
if (can <= 0 || can > 51)
{
system("cls");
cout << "Warning: The amount of products entered is not valid, try again";
return add();
}
for (int p = 1; p <= can;)
{
if (i < 51)
{
if (k <= 51) // In this part, consecutive numbers are generated automatically
{
cout << "\nNumber of order: ";
cout << k;
cout << endl;
product[i].numor = k;
k++;
}
cin.ignore();
cout << "Name of product: ";
getline(cin, product[i].descr);
intro_code();
cout << "Quantity to sell: "; cin >> product[i].cant;
cout << "unit price: $"; cin >> product[i].preuni;
product[i].subt = product[i].preuni * product[i].cant;
cout << "Subtotal: $" << product[i].subt;
product[i].IVA = product[i].subt * 0.16;
cout << "\nIVA: $" << product[i].IVA;
product[i].total = product[i].subt + product[i].IVA;
cout << "\nTotal price: $" << product[i].total;
cout << "\n-------------------------------------------------------------------------------";
cout << endl;
i++;
}
p++;
}
}
/*In this function the product code is entered, if the user enters a code
less than or greater than 5 characters the program displays an error message and allows the
user try again.*/
void intro_code()
{
char hello[10];
int xyz;
do {
cout << "Code of product (5 digits): ";
cin.getline(hello, 10, '\n');
if (strlen(hello) != 5)
{
cout << "The data entered is incorrect, try again ...";
cout << endl;
return intro_code();
}
else
{
xyz = val_code(hello);
}
} while (xyz == 0);
product[i].cod = hello;
}
/*As the requirement for "product code" is that it does not contain letters, special characters or blank spaces
create the function val_code to go through each character entered in the code, check character by character with the isdigit function
to see if the character is numeric or not, if it is not numeric it prints a warning message and allows the user to try again
without leaving the console.*/
int val_code(char hello[]) {
int abc;
for (abc = 0; abc < strlen(hello); abc++) {
if (!(isdigit(hello[abc]))) {
cout << "The data entered is incorrect, try again ...";
cout << endl;
return 0;
}
}
return 1;
}
void table()
{
int c = k, m = 7;
system("cls");
cout << endl;
cout << "Table of created products";
cout << endl;
cout << endl;
cout << " number of order ";
cout << "| Name of product |";
cout << " Product code |";
cout << " Amount |";
cout << " Unit price |";
cout << " Subtotal |";
cout << " IVA |";
cout << " total price |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
for (int L = 2; L <= c; L++)
{
cout << " ";
cout << "| |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
}
for (int h = 1; h < c; h++)
{
gotoxy(8, m);
cout << product[h].numor;
gotoxy(20, m);
cout << product[h].descr;
gotoxy(52, m);
cout << product[h].cod;
gotoxy(70, m);
cout << product[h].cant;
gotoxy(83, m);
cout << "$" << product[h].preuni;
gotoxy(96, m);
cout << "$" << product[h].subt;
gotoxy(107, m);
cout << "$" << product[h].IVA;
gotoxy(119, m);
cout << "$" << product[h].total;
m = m + 4;
}
cout << "\n\n\n";
system("pause");
system("cls");
}
void gotoxy(int x, int y)
{
HANDLE hcon;
hcon = GetStdHandle(STD_OUTPUT_HANDLE);
COORD dwPos;
dwPos.X = x;
dwPos.Y = y;
SetConsoleCursorPosition(hcon, dwPos);
}
Thank you very much in advance :)
The main reason for this problem is that after the size of the console changes, the position of the symbols you draw has also changed. At the same time, the line break determined by cout<<endl; also has a problem. For example, after the window becomes larger, the line length of the console becomes larger, but cout<<endl; is still the original line length.
However, there is no good solution. I suggest you directly set the console size and m=5, m=m+2.
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<string>
#include<ctype.h>
#include <stdio.h>
#include <windows.h>
#include<iomanip>
using namespace std;
struct products
{
int numor{},
cant{};
float preuni{},
subt{},
IVA{},
total{};
string cod{};
string descr{};
}product[51];
void add();
void intro_code();
int val_code(char codigo[]);
void table();
void gotoxy(int x, int y);
int i = 1; //Product No. (counter)
int k = 1; //Consecutive number (counter)
int main()
{
HWND console = GetConsoleWindow();
RECT r;
GetWindowRect(console, &r);
MoveWindow(console, r.left, r.top, 1400, 400, TRUE);
char opc;
cout << " Welcome ";
cout << endl;
cout << "\n1.- Add product.";
cout << "\n2.- Delete product.";
cout << "\n3.- Table of created products.";
cout << "\n4.- Exit";
cout << endl;
cout << "\nWhat do you want to do today?: "; cin >> opc;
switch (opc)
{
case '1':
system("cls");
cout << "\nAdd product";
add();
system("pause");
system("cls");
return main();
case '2':
cout << "\nDelete product";
system("cls");
return main();
case '3':
table();
return main();
case '4':
exit(EXIT_SUCCESS);
default:
system("cls");
cout << "Warning: the data entered is not correct, try again.\n\n";
return main();
}
return 0;
}
void add()
{
int can;
cout << "\nHow many products do you want to register?: "; cin >> can;
if (can <= 0 || can > 51)
{
system("cls");
cout << "Warning: The amount of products entered is not valid, try again";
return add();
}
for (int p = 1; p <= can;)
{
if (i < 51)
{
if (k <= 51) // In this part, consecutive numbers are generated automatically
{
cout << "\nNumber of order: ";
cout << k;
cout << endl;
product[i].numor = k;
k++;
}
cin.ignore();
cout << "Name of product: ";
getline(cin, product[i].descr);
intro_code();
cout << "Quantity to sell: "; cin >> product[i].cant;
cout << "unit price: $"; cin >> product[i].preuni;
product[i].subt = product[i].preuni * product[i].cant;
cout << "Subtotal: $" << product[i].subt;
product[i].IVA = product[i].subt * 0.16;
cout << "\nIVA: $" << product[i].IVA;
product[i].total = product[i].subt + product[i].IVA;
cout << "\nTotal price: $" << product[i].total;
cout << "\n-------------------------------------------------------------------------------";
cout << endl;
i++;
}
p++;
}
}
/*In this function the product code is entered, if the user enters a code
less than or greater than 5 characters the program displays an error message and allows the
user try again.*/
void intro_code()
{
char hello[10];
int xyz;
do {
cout << "Code of product (5 digits): ";
cin.getline(hello, 10, '\n');
if (strlen(hello) != 5)
{
cout << "The data entered is incorrect, try again ...";
cout << endl;
return intro_code();
}
else
{
xyz = val_code(hello);
}
} while (xyz == 0);
product[i].cod = hello;
}
/*As the requirement for "product code" is that it does not contain letters, special characters or blank spaces
create the function val_code to go through each character entered in the code, check character by character with the isdigit function
to see if the character is numeric or not, if it is not numeric it prints a warning message and allows the user to try again
without leaving the console.*/
int val_code(char hello[]) {
int abc;
for (abc = 0; abc < strlen(hello); abc++) {
if (!(isdigit(hello[abc]))) {
cout << "The data entered is incorrect, try again ...";
cout << endl;
return 0;
}
}
return 1;
}
void table()
{
int c = k, m = 5;
system("cls");
cout << endl;
cout << "Table of created products";
cout << endl;
cout << endl;
cout << " number of order ";
cout << "| Name of product |";
cout << " Product code |";
cout << " Amount |";
cout << " Unit price |";
cout << " Subtotal |";
cout << " IVA |";
cout << " total price |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
for (int L = 2; L <= c; L++)
{
cout << " ";
cout << "| |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
}
for (int h = 1; h < c; h++)
{
gotoxy(8, m);
cout << product[h].numor;
gotoxy(20, m);
cout << product[h].descr;
gotoxy(52, m);
cout << product[h].cod;
gotoxy(70, m);
cout << product[h].cant;
gotoxy(83, m);
cout << "$" << product[h].preuni;
gotoxy(96, m);
cout << "$" << product[h].subt;
gotoxy(107, m);
cout << "$" << product[h].IVA;
gotoxy(119, m);
cout << "$" << product[h].total;
m = m + 2;
}
cout << "\n\n\n";
system("pause");
system("cls");
}
void gotoxy(int x, int y)
{
HANDLE hcon;
hcon = GetStdHandle(STD_OUTPUT_HANDLE);
COORD dwPos;
dwPos.X = x;
dwPos.Y = y;
SetConsoleCursorPosition(hcon, dwPos);
}
In addition, it is not recommended that you use cmd to make gui.

How to update a while loop with multiple if statements?

I am working on the "checkout" process of my vending machine code. I want to write it so that the program will keep asking for the amount needed from the user until all the money is entered. However, this code segment does not completely work.
"Checkout" Segment of Code:
while (money < total) {
float amountOwed = total - money;
cout << "Please insert another $" << amountOwed << endl;
cout << "Enter amount: $" << flush;
float payment;
cin >> payment;
}
if (money > total) {
float change = money - total;
cout << "Thank you! You have $" << change << " change." << endl;
}
if (money == total) {
cout << "Thank you! Have a nice day!." << endl;
}
Full code below:
#include <iostream>
#include <iomanip>
using namespace std;
string menuItems[5] = { "Popcorn", "Coconut Clusters" , "Granola Bar" , "Trail Mix" , "Chocolate" };
float cost[5] = { 2, 3, 2.50, 1.50, 1 };
void vendingMachine() {
for (int i = 0; i < 5; i++)
cout << i + 1 << ". " << menuItems[i] << ": $" << cost[i] << endl;
}
int main() {
cout.precision(2);
cout << std::fixed;
cout << "Vending Machine" << endl;
cout << "----Items------" << endl;
vendingMachine();
cout << "Enter 0 to checkout" << endl;
float total;
total = 0;
int item;
do {
cout << "Enter your selection: " << flush;
cin >> item;
item = item - 1;
//here will be printed : $0 has been added to cart even if you pressed 0 and what to escape
//is it possible to fix this??
cout << menuItems[item] << ": $" << cost[item] << " has been added to cart." << endl;
total = total + cost[item];
} while (item != -1);
cout << " " << endl;
cout << "Proceding to checkout..." << endl;
cout << "========================" << endl;
cout << "Amount due: $" << total << endl;
cout << "Insert money here: $" << flush;
float money;
cin >> money;
while (money < total) {
float amountOwed = total - money;
cout << "Please insert another $" << amountOwed << endl;
cout << "Enter amount: $" << flush;
float payment;
cin >> payment;
}
if (money > total) {
float change = money - total;
cout << "Thank you! You have $" << change << " change." << endl;
}
if (money == total) {
cout << "Thank you! Have a nice day!." << endl;
}
return 0;
}
In this loop:
while (money < total) {
you are not modifying money or total so the loop will never exit.
You probably want to update money like this:
while (money < total) {
// ...
cin >> payment;
money += payment;
}

Attempting to loop back to the beginning to run my program again

I am currently writing a code where in my main function I am just calling other functions. I am attempting to reloop back to the begining so the user can run the program again. The main function is just to call functions so my question is I know it is not possible to go back to the main function, but is it possible to create a function that will loop all other functions again? I feel as though I tried everything and continue to get infinite loops. I attached my code.
To condense the code please understand that all variables/classes are declared
void instructions();
void full_outputs(string, double, double, double);
int main()
{
instructions();
employee_num = employee_ID();
//cout << employee_num << " This is the employee ID."<<endl;
base_salary = baseSalary();
//cout << base_salary << " This is the employee's base salary." <<endl;
per_commission = percentage_commission();
//cout << per_commission << " This is the employee's percentage commission." << endl;
base_commission = base_and_com(base_salary, per_commission);
cout<< base_commission << "This is the total base salary with comission" << endl;
gross_pay = grossPay(base_commission);
//cout << gross_pay << "This is the gross pay"<<endl;
state_tax_hold = stateTax_hold(gross_pay);
//cout<< state_tax_hold << "This is the state tax hold on the amount" <<endl;
fica_total = ficaTotal(gross_pay);
//cout << fica_total << " This is the fica hold on the amount" <<endl;
fed_tax = fedTax(gross_pay);
//cout << fed_tax << " THis is the federal tax hold on the amount" << endl;
total_tax_hold = withholding_total(state_tax_hold, fica_total, fed_tax);
//cout << total_tax_hold << " This is the total tax withholding" << endl;
net_pay = netPay(total_tax_hold, gross_pay);
//cout << net_pay << " This is the total net pay" << endl;
full_outputs(employee_num, gross_pay, total_tax_hold, net_pay);
return 0;
}
void instructions()
{
cout << " This program will process sales employee's base salary \n";
cout << " and their percentage commission. \n";
cout << " You will be prompted to enter the employee's ID, base salary \n";
cout << " and percentage commission. \n";
cout << " \n";
cout << " The program will terminate if unspecified characters are used. \n";
}
string employee_ID()
{
string employee_num;
cout << " Please enter the employees eight digit ID number" << endl;
cin >> employee_num;
return employee_num;
}
double baseSalary()
{
double base_salary;
cout << " Please enter the employees base salary " << endl;
cin >> base_salary;
return base_salary;
}
float percentage_commission()
{
float per_commission;
cout << " Please enter the employees percentage commission."<< endl;
cout << " Please do not enter the percent symbol." << endl;
cout << " Percentage commission is between 0.05% - 10%" << endl;
cin >> per_commission;
while ((per_commission < 0.05)||(per_commission > 10))
{
cout << "The commission rate is not between 0.05% and 10%" << endl;
cout << "Please try again " << endl;
cin >> per_commission;
}
per_commission = per_commission / PERCENT_TO_DECIMAL;
return per_commission;
}
double base_and_com(double base_salary, float per_commission)
{
double base_commission;
double total;
total = base_salary*per_commission;
base_commission = total + base_salary;
return base_commission;
}
double grossPay(double base_commission)
{
double gross_pay;
gross_pay = base_commission;
cout << fixed << showpoint << setprecision(2);
return gross_pay;
}
double stateTax_hold(double gross_pay)
{
double state_tax_hold;
state_tax_hold= gross_pay*STATE_TAX;
return state_tax_hold;
}
double ficaTotal (double gross_pay)
{
double fica_total;
fica_total = gross_pay* FICA;
return fica_total;
}
double fedTax (double gross_pay)
{
double fed_tax;
if (gross_pay <= 500)
{
fed_tax = gross_pay * FEDERAL_TAX_UNDER;
}
else
{
fed_tax = gross_pay * FEDERAL_TAX_OVER;
}
return fed_tax;
}
double withholding_total(double fed_tax, double fica_total, double state_tax_hold )
{
double tax_withholding_total;
tax_withholding_total = fed_tax + fica_total + state_tax_hold;
cout << fixed << showpoint << setprecision(2);
return tax_withholding_total;
}
double netPay(double total_tax_hold, double gross_pay)
{
double net_pay;
net_pay = (gross_pay - total_tax_hold);
cout << fixed << showpoint << setprecision(2);
return net_pay;
}
void full_outputs(string employee_num, double gross_pay, double total_tax_hold, double net_pay)
{
cout << " The employee ID : " << right << employee_num << endl;
cout << " The gross pay is: " << right << gross_pay << endl;
cout << " The total tax withholding amount is : " << right << total_tax_hold << endl;
cout << " The net pay is: " << right << net_pay << endl;
}
As you know, in main you can just have a while loop with the code you want to repeat inside it:
int main()
{
// this will loop forever, until you explicitly break or return
while (true) {
// your code here
}
}
... but since you are constrained by the artificial limitation of only having function calls in main...
void run()
{
// this will loop forever, until you explicitly break or return
while (true) {
// your code here
}
}
int main()
{
run();
}

How to loop but reject non-numerical inputs?

How do I make a function that will terminate the program if the user says e, and loop if the user presses l at any time?
How do I make the program reask the user for number input if the user inputs letters instead of numbers? Currently, the program terminates when I input blah, for instance. My obstacle is the bool die definition: I'm not sure how to use bool die to loop instead of die (my teacher required bool die usage.)
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
bool die(const string & msg);
int main() {
// declaring variables:
unsigned QUARTERS;
unsigned DIMES;
unsigned NICKELS;
unsigned PENNIES;
double total;
cout << "********************************************************" << endl;
cout << " Welcome to Crazy Coin Counter! " << endl;
cout << "********************************************************" << endl << endl;
// user input:
//QUARTERS
do {
cout << " # QUARTERS: ";
cin >> QUARTERS;
if (cin){
if (QUARTERS < 1000)
cout << " --> Input Successful!" << endl;
}
else die(" --> :( Input Unsuccessful!");
cout << " You must put in less than 1000 quarters! Please try again." << endl << endl << endl;
} while (QUARTERS >= 1000 );
//DIMES
do{
cout << endl << " # DIMES: ";
cin >> DIMES;
if (cin){
if (DIMES < 1000)
cout << " --> Input Successful!" << endl;
}
else die(" --> :( Input Unsuccessful!");
if (DIMES >= 1000)
cout << " You must put in less than 1000 dimes! Please try again." << endl << endl << endl;
} while (DIMES >= 1000);
//NICKELS
do {
cout << endl << " # NICKLES: ";
cin >> NICKELS;
if (cin){
if (NICKELS < 1000)
cout << " --> Input Successful!" << endl;
}
else die(" --> :( Input Unsuccessful!");
if (NICKELS >= 1000)
cout << " You must put in less than 1000 nickels! Please try again." << endl << endl << endl;
} while (NICKELS >= 1000);
//PENNIES
do {
cout << endl << " # PENNIES: ";
cin >> PENNIES;
if (cin){
if (PENNIES < 1000)
cout << " --> Input Successful!" << endl;
}
else die(" --> :( Input Unsuccessful!");
if (PENNIES >= 1000)
cout << " You must put in less than 1000 pennies! Please try again." << endl;
} while (PENNIES >= 1000);
// calculations:
total = (QUARTERS * 0.25) + (DIMES * 0.1) + (NICKELS * 0.05) + (PENNIES * 0.01);
// output:
cout << endl <<endl<< "Congrats! You have $" << total << " worth of coins! " << endl << endl << endl;
}
// function definition
bool die(const string & msg){
cout << " " << msg << endl;
exit(EXIT_FAILURE);
}
Try something like this:
while ( true ) // Loop forever
{
cout << "Enter 'e' to exit:";
std::string answer;
getline(cin, answer);
if (answer == "e")
{
break; // Break out of the loop
}
else
{
cout << "\nWrong answer.\n";
continue; // The continue would start at the top of the loop.
}
}
There are many other techniques that you can find by searching StackOverflow for "c++ terminate loop".
Edit 1: Checking numerical input
The simplest method for checking numerical input is to test the result of inputting the number:
unsigned int quarters; // Using unsigned because quantities can't be negative.
cout << "Enter number of quarters: ";
if (cin >> quarters) // Input and test in same statement.
{
cout << "Your total is " << (quarters * 0.25) << "\n";
}
else
{
// Handle incorrect input
cout << "Invalid input, try again.\n";
}

I'm getting a unassigned variable error at the account1 after the GetTransfer. I can not figure out what logic error i have messed up on

Getting an unassigned variable error after the GetTransfer portion of the code. It is claiming account1 is the unassigned variable but from what i can see i have declared it. i have tried multiple times to correct it and i just can figure it out.
#include <iostream>
#include <conio.h>
using namespace std;
// Chance Pinkerton
// December 3, 2013
// CaseProject2Chapter3
struct bankInfo
{
int accountNum;
double startBal;
double endBal;
};
int main()
{
bankInfo account1;
bankInfo account2;
double transferAmt;
int GetAccount1();
int GetAccount2();
double GetBal1();
double GetBal2();
double GetTransfer();
account1.accountNum = GetAccount1();
while (account1.accountNum < 1000 || account1.accountNum > 9999)
{
cout << "Error. That account does not exsist." << endl;
account1.accountNum = GetAccount1();
}
GetBal1();
account2.accountNum = GetAccount2();
while (account2.accountNum < 1000 || account2.accountNum > 9999)
{
cout << "Error. That account number doesnt exsist." << endl;
account2.accountNum = GetAccount2();
}
if (account2.accountNum == account1.accountNum)
{
cout << "Error. Account numbers can not be the same " << endl;
account2.accountNum = GetAccount2();
}
GetBal2();
transferAmt = GetTransfer();
account1.accountNum = (account1.accountNum % 5) + (account1.accountNum * 10);
account2.accountNum = (account2.accountNum % 5) + (account2.accountNum * 10);
account1.endBal;
account2.endBal;
while (account1.endBal < 0)
{
cout << "Error. Account balance can not be negative." << endl;
GetTransfer();
if (account1.endBal < 10)
{
cout << "Warning. Account balance will be below $10.00 " << endl;
}
}
account1.endBal = account1.startBal - transferAmt;
account2.endBal = account2.startBal + transferAmt;
cout << "Account number 1: " << account1.accountNum << endl;
cout << "Starting balance: " << account1.startBal << endl;
cout << "Ending balance: " << account1.endBal << endl;
cout << "Account number 2: " << account2.accountNum << endl;
cout << "Starting balance: " << account2.startBal << endl;
cout << "Ending balance: " << account2.endBal << endl;
getch();
return 0;
}
int GetAccount1()
{
int accountNum;
cout << "Please enter your account number " << endl;
cin >> accountNum;
return accountNum;
}
int GetAccount2()
{
int accountNum;
cout << "Please enter the second account number " << endl;
cin >> accountNum;
return accountNum;
}
double GetBal1()
{
double startBal;
cout << "Enter your account balance " << endl;
cin >> startBal;
return startBal;
}
double GetBal2()
{
double startBal;
cout << "Enter the second account balance " << endl;
cin >> startBal;
return startBal;
}
double GetTransfer()
{
double transferAmt;
cout << "How much would you like to transfer to the second account " << endl;
cin >> transferAmt;
return transferAmt;
}
These two statements do exactly nothing, and are likely the source of the warning the compiler is giving you:
account1.endBal;
account2.endBal;
Furthermore, I think you need to actually capture the return value of GetTransfer() here, perhaps into transferAmt:
GetTransfer();
You probably need to rethink this entire while loop, especially taking into account how transferAmt relates to account1.endBal:
while (account1.endBal < 0)
{
cout << "Error. Account balance can not be negative." << endl;
GetTransfer();
if (account1.endBal < 10)
{
cout << "Warning. Account balance will be below $10.00 " << endl;
}
}
For example, you don't want to update endBal until you know the transfer will succeed. Furthermore, your low-balance warning is in completely the wrong place.