C++ Clearing streams, and testing input - multiple issues - c++

I'm currently learning C++ in class, and I have 3 problems with validation. My professor asked me to not user stringstream for validating input. I'm running into a problem where if the user enters two characters 'rr' for example, the error message displays twice (Which is why I just used stringstream originally to test for the first incorrect character). The second problem is if they enter two values, such as -45 -56. Somehow, the second value of 56 is coming to be positive after the loop and the program is running with it, even after I cleared the stream.
Lastly, if a user enters a float into an int, it truncates it - but how do I prevent that from happening? E.g. I only want an int entered. I tried less than and greater then with no avail. Notice in the below posted code, I do not have the truncating problem because the user input is a double - but I think someone should understand the theory of what I'm asking.
Please let me know if the formatting on here is not correct, I was having some issues with pasting it in the block, but it looks like it may be alright now.
Thank you!
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const double EARTH_G = 1, SPACE_G = 0, EARTH_MOON_G = .17, VENUS_G = .90, MARS_G = .38,
MERCURY_G = .38, JUPITER_G = 2.36, SATURN_G = .92, URANUS_G = .89,
NEPTUNE_G = 1.14, PLUTO_G = .07;
double userWeight;
enum planets {Earth = 1, Space, Moon, Venus, Mars, Mercury, Jupiter, Saturn, Uranus,
Neptune, Pluto};
/*Validates input by making sure checking for only numbers greater than 0*/
{
bool flag = 0;
while (flag == 0)
{
cout << "What is your earth weight in lbs?" << endl;
cin >> userWeight;
if (!static_cast<double>(userWeight) || userWeight < 0)
{
cout << "Invalid Input.\nPlease enter only positive numbers." << endl;
cin.clear();
cin.ignore();
}
else
{
flag = 1;
}
}
}
{
//Displays menu with choices, and allows produces output based on choice.
//Loops while input is invalid.
bool flag = 0;
int choice;
double newWeight;
while (flag == 0)
{
cout << "Select a place in space with a number to see your weight there!\n\n";
cout << "1 - Earth\n\n2 - Space\n\n3 - Earth's Moon\n\n4 - Venus\n\n5 - Mars\n\n"
<< "6 - Mercury\n\n7 - Jupiter\n\n8 - Saturn\n\n9 - Uranus\n\n10 - Neptune\n\n11 - Pluto\n\n";
cout << "Select 1 - 11:\n";
cin >> choice;
switch (choice)
{
case(Earth):
{
newWeight = (userWeight * EARTH_G);
cout << "Your weight on earth is " << fixed << setprecision(1)
<< newWeight << endl;
flag = 1;
break;
}
case(Space):
{
newWeight = (userWeight * SPACE_G);
cout << "Your weight in space is " << fixed << setprecision(1)
<< newWeight << endl;
flag = 1;
break;
}
case(Moon):
{
newWeight = (userWeight * EARTH_MOON_G);
cout << "Your weight on the Earth's moon is " << fixed << setprecision(1)
<< newWeight << endl;
flag = 1;
break;
}
case(Venus):
{
newWeight = (userWeight * VENUS_G);
cout << "Your weight on Venus is " << fixed << setprecision(1) << newWeight << endl;
flag = 1;
break;
}
case(Mars):
{
newWeight = (userWeight * MARS_G);
cout << "Your weight on Mars is " << fixed << setprecision(1) << newWeight << endl;
flag = 1;
break;
}
case(Mercury):
{
newWeight = (userWeight * MERCURY_G);
cout << "Your weight on Mercury is " << fixed << setprecision(1) << newWeight << endl;
flag = 1;
break;
}
case(Jupiter):
{
newWeight = (userWeight * JUPITER_G);
cout << "Your weight on Jupiter is " << fixed << setprecision(1) << newWeight << endl;
flag = 1;
break;
}
case(Saturn):
{
newWeight = (userWeight * SATURN_G);
cout << "Your weight on Saturn is " << fixed << setprecision(1) << newWeight << endl;
flag = 1;
break;
}
case(Uranus):
{
newWeight = (userWeight * URANUS_G);
cout << "Your weight on Uranus is " << fixed << setprecision(1) << newWeight << endl;
flag = 1;
break;
}
case(Neptune):
{
newWeight = (userWeight * NEPTUNE_G);
cout << "Your weight on Neptune is " << fixed << setprecision(1) << newWeight << endl;
flag = 1;
break;
}
case(Pluto):
{
newWeight = (userWeight * PLUTO_G);
cout << "Your weight on Pluto is " << fixed << setprecision(1) << newWeight << endl;
flag = 1;
break;
}
default:
{
cout << "Invalid Input." << endl;
cin.clear();
cin.ignore();
}
}
}
}
}

According to http://en.cppreference.com/w/cpp/io/basic_istream/ignore , the basic, no parameters ignore only removes one character from the input stream. According to the example provided in the above documentation link, the recommended usage is
input.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
To consume the entire line. Note the additional include statement required to get numeric_limits::max.

Related

C++ Switch statement using strings

I am fully aware that switch must be used with int but my assignment is requiring me to use switch in regards to user input which will be strings. I've looked and I've seen some mentioning stoi but I'm not sure if that is what my professor is expecting b/c we have not been introduced to it yet. I'm completely new to C++ so I'm still learning and this code is not completed yet but can anyone please help me with this?
int main()
{
// Declare Constant variables
const float DISC_GOLF_RETAIL = 14.96;
const float ULTIMATE_RETAIL = 20.96;
const double DISCOUNT1 = 8;
const float DISCOUNT2 = .16;
const float DISCOUNT3 = .24;
const float DISCOUNT4 = .32;
const double DEC = 100;
// Declare variables
double quantity;
double pricePerDisc;
double totalSavings;
double total;
char userInput;
float discount;
string discType;
string disc1 = "Ultimate Disc";
string disc2 = "Disc-Golf Disc";
// Display title
cout << "Welcome to the Flying-Disc Shop!" << "\n" << endl;
// Prompt the user for input
cout << "Enter 'u' for ultimate discs and 'g' for disc golf: ";
cin >> (userInput);
cout << endl;
switch (discType)
{
case 1: userInput=='u' || 'U';
discType = disc1;
pricePerDisc = ULTIMATE_RETAIL;
break;
case 2: userInput=='g' || 'G';
discType = disc2;
pricePerDisc = DISC_GOLF_RETAIL;
break;
default:
cout << "Invalid disc type." << endl;
return 0;
}
cout << "Enter the number of Ultimate Disc(s): ";
cin >> (quantity);
cout << endl;
cout << "------------Receipt------------" << endl;
if (quantity>5 && quantity<=9)
{
discount = DISCOUNT1 / DEC;
totalSavings = (pricePerDisc * quantity) * discount;
}
else if (quantity>10 && quantity<=19)
{
discount = DISCOUNT2;
totalSavings = (pricePerDisc * quantity) * discount;
}
else if (quantity>20 && quantity<=29)
{
discount = DISCOUNT3;
totalSavings = (pricePerDisc * quantity) * discount;
}
else if (quantity>= 30)
{
discount = DISCOUNT4;
}
totalSavings = (pricePerDisc * quantity) * discount;
total = quantity * pricePerDisc - totalSavings;
cout << "Disc Type: " << discType << endl;
cout << "Quantity: " << quantity << endl;
cout << "Pricer per Disc: " << "$ " << fixed << setprecision(2)
<< pricePerDisc << endl;
cout << "Total Savings: " << "$ " << "-" << fixed << setprecision(2)
<< totalSavings << endl;
cout << "Total: " << "$ " << total << fixed << setprecision(2) << endl;
}
For single char responses, you can use the switch/case statement:
switch (userInput)
{
case 'g':
case 'G':
/* ... */
break;
case 'u':
case 'U':
// ...
break;
default:
// ...
break;
}
A single character can be treated differently than a string. A string is usually consists of more than one character.

Why is failed input validation returning me to the start of my program?

Really sorry if this is a dumb question. I know it must have a super easy solution but I've been staring at this for so long I can't see it. It doesn't help that I'm really new at this either.
Long story short for some reason entering an invalid input past the first time returns me back to my menu, and sometimes also asks me to enter weight immediately after instead of allowing me to enter a menu choice. It's just all around broken and I don't know why. Thanks.
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
bool loopFlag = true;
bool loopFlagTwo = true;
int choice = 0;
int time = 0;
float weightPounds = 0;
float weight = 0;
const int BIKING = 8;
const int RUNNING = 10;
const int LIFTING = 3;
const float YOGA = 2.5;
int main()
{
cout << "Welcome to my Fitness Center" << endl;
do
{
cout << "\n\t____________________________________________________________" << endl;
cout << "\n\t\t\tMy Fitness Center" << endl;
cout << "\t\t\tActivity System" << endl;
cout << "\t____________________________________________________________" << endl;
cout << "\t\t\t Main Menu\n" << endl;
cout << "\t\t\t1) Stationary Bike" << endl;
cout << "\t\t\t2) Treadmill" << endl;
cout << "\t\t\t3) Weight Lifting" << endl;
cout << "\t\t\t4) Hatha Yoga" << endl;
cout << "\t\t\t5) End" << endl;
cout << "\t____________________________________________________________" << endl;
cout << "\n\nEnter the workout that you wish to track, or end to exit:" << endl;
do
{
cin >> choice;
if (cin.fail() || choice > 5 || choice < 1)
{
cout << "Invalid choice. Please choose from option 1 through 5." << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else if (choice == 5)
{
return 0;
}
else
{
loopFlag = false;
}
}
while (loopFlag);
do
{
cout << "\nPlease enter your weight in pounds: " << endl;
cin >> weightPounds;
if (cin.fail() || weightPounds <= 0)
{
cout << "Invalid weight entry!" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else
{
loopFlag = false;
}
}
while (loopFlag);
weight = weightPounds / 2.2;
cout << "\nYour weight is: \n" << fixed << setprecision(1) << weight << " kilograms." << endl;
if (choice == 1)
{
do
{
cout << "For how many minutes did you do this activity? " << endl;
cin >> time;
if (cin.fail() || time <= 0)
{
cout << "Invalid time entry!" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else
{
loopFlag = false;
}
}
while (loopFlag);
}
}
while (choice != 5);
return 0;
}
You need to set loopFlag to true before every do...while() you have, or use another flag, because after the first do...while(), loopFlag is always false.

Making program so that if statement is assigned proper number

I'm trying to making it so that if the planet name is not found in the array, it will set the code variable to -1, but it seems to always make the variable -1 regardless. If I don't have the else statement, the program works fine, but then the switch's default statement doesn't work. How do I make it so that the code variable gets assign the proper value if the planet name is entered incorrectly.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
//declare arrays
string planetNames[8] = { "MERCURY", "VENUS", "EARTH", "MARS", "JUPITER", "SATURN", "URANUS", "NEPTUNE" };
double gravity[8] = { 0.37, 0.78, 1, 0.38, 2.64, 1.16, 1.07, 1.21 };
//declare variable
string name = " ";
double weight = 0.0;
string planet = " ";
double finalWeight = 0.0;
int code = 0;
//explain program to user
cout << "In this program you will enter your first and last name, then your weight, and finally the planet that you want to know your weight on" << endl << endl;
//get input
cout << "What is your first and last name: ";
getline(cin, name);
cout << "How much do you weigh: ";
cin >> weight;
cout << "Which planet would you like to know how much you weigh on: ";
cin >> planet;
//capitalize planet name
transform(planet.begin(), planet.end(), planet.begin(), toupper);
while (weight != -1)
{
for (int x = 0; x < 8; x++)
{
if (planet == planetNames[x])
code = x; //THIS IS WHERE THE PROBLEM IS!!!!!!!!!
else
code = -1;
//end if
}//end for
//calculate and display weights
switch (code)
{
case 0:
finalWeight = weight * gravity[code];
cout << "The weight of " << name << " on " << planetNames[code] << " would be " << finalWeight << "lbs" << endl;
break;
case 1:
finalWeight = weight * gravity[code];
cout << "The weight of " << name << " on " << planetNames[code] << " would be " << finalWeight << "lbs" << endl;
break;
case 2:
finalWeight = weight * gravity[code];
cout << "The weight of " << name << " on " << planetNames[code] << " would be " << finalWeight << "lbs" << endl;
break;
case 3:
finalWeight = weight * gravity[code];
cout << "The weight of " << name << " on " << planetNames[code] << " would be " << finalWeight << "lbs" << endl;
break;
case 4:
finalWeight = weight * gravity[code];
cout << "The weight of " << name << " on " << planetNames[code] << " would be " << finalWeight << "lbs" << endl;
break;
case 5:
finalWeight = weight * gravity[code];
cout << "The weight of " << name << " on " << planetNames[code] << " would be " << finalWeight << "lbs" << endl;
break;
case 6:
finalWeight = weight * gravity[code];
cout << "The weight of " << name << " on " << planetNames[code] << " would be " << finalWeight << "lbs" << endl;
break;
case 7:
finalWeight = weight * gravity[code];
cout << "The weight of " << name << " on " << planetNames[code] << " would be " << finalWeight << "lbs" << endl;
break;
default:
cout << "Invalid planet name" << endl;
}//end switch
cout << endl;
cout << "How much do you weigh(-1 to end the program): ";
cin >> weight;
cout << "Which planet would you like to know how much you weigh on: ";
cin >> planet;
transform(planet.begin(), planet.end(), planet.begin(), toupper);
}//end while
system("pause");
return 0;
}
You need to break the loop after you have found the matching planet name, otherwise the loop keeps searching, and the next name won't match so code is set to -1.
Also: for efficiency and clarity: set code = -1 before the loop and only set to x on a match:
code = -1;
for (int x = 0; x < 8; x++)
{
if (planet == planetNames[x])
{
code = x; //THIS IS WHERE THE PROBLEM IS!!!!!!!!!
break; // And now it's gone ;-)
}
}
this if is fine.
for example if you type mars, code will get value 3.
But then in next step of loop you will set it again to -1 ;)
Break the loop when result is found.
Advice:
Split this part of code to new function.

Having troubles w/functions and arrays

I'm Using Visual studio (C++) in a class that I am taking, I've had to teach myself functions, and I've hit a small snag in the road that I'd appreciate some advice on.
What I'm having trouble with, is the part of the assignment that states i must
"Utilize a function that prints (not find) the largest/average/smallest commissions"
The way I read this, I'm assuming she only wants it to print, and not do calculations in the function.
A friend suggested I try void print(etc) However I'm unsure how to grab the calculation in main and give it to the function I'm trying to print, or am i going at it all wrong?
I've commented out the portion of code I was trying to function. You can also find it at the very bottom of the code.
Any suggestions/help is greatly appreciated, as most of what I've looked up haven't really dealt with this problem (that I've found)
#include <iostream>
#include <iomanip>
using namespace std;
#define TITLE "Alva's"
#define STANDARD 0.05
#define HYBRID 0.10
#define ELECTRIC 0.15
#define HOLD 50
void dashLine();
int getSalesId();
int runProgram();
char vehicleType();
double sellingPrice();
void print(double largeSmallAverage);
int main()
{
int tot_count,
id_num[HOLD], //* ID
r_ay = 0, //* array
s_count, //*standard
h_count, //*Hybrid
e_count, //*electric
hold_id, //*array Id
compare, //*Pass
change, //*change made when change has value
yesno;
double tot_standard,
tot_hybrid,
tot_electric,
tot_price,
price[HOLD],
hold_price, //*Array hold
comm_l, //* Large
comm_s, //* Small
hold_comm, //*Array hold
avg_comm,
tot_commission,
commission[HOLD];
char car[HOLD],
temp_car;
tot_count = 0;
s_count = 0;
h_count = 0;
e_count = 0;
tot_price = 0;
tot_standard = 0;
tot_hybrid = 0;
tot_electric = 0;
cout << "\n" << TITLE << " Commission Calculator";
yesno = runProgram();
while (yesno == 1)
{
dashLine();
id_num[r_ay] = getSalesId();
car[r_ay] = vehicleType();
price[r_ay] = sellingPrice();
tot_price += price[r_ay];
switch (car[r_ay])
{
case 'S':
case 's':
commission[r_ay] = (price[r_ay] * STANDARD);
tot_standard += commission[r_ay];
s_count++;
break;
case 'H':
case 'h':
commission[r_ay] = (price[r_ay] * HYBRID);
tot_hybrid += commission[r_ay];
h_count++;
break;
case 'E':
case 'e':
commission[r_ay] = (price[r_ay] * ELECTRIC);
tot_electric += commission[r_ay];
e_count++;
break;
}
cout << "\n The commission for this sale, for Employee ID: " << fixed << setprecision(0) << id_num[r_ay] << " is:$ " << fixed << setw(5) << setprecision(2) << commission[r_ay];
cout << "\n";
yesno = runProgram();
r_ay++;
if (r_ay >= HOLD)
yesno = 0;
}
tot_count = (s_count + h_count + e_count);
tot_commission = (tot_standard + tot_hybrid + tot_electric);
{
cout << "\n Number of standard vehicle commissions calculated = " << fixed << setw(8) << setprecision(0) << s_count;
cout << "\n Number of hybrid vehicle commissions calculated = " << fixed << setw(8) << h_count;
cout << "\n Number of electric vehicle commissions calculated = " << fixed << setw(8) << e_count;
cout << "\n Number of vehicle commissions calculated = " << fixed << setw(8) << tot_count;
cout << "\n Total Overall price calculated =$ " << fixed << setw(8) << setprecision(2) << tot_price;
cout << "\n Total amount of standard vehicle commissions =$ " << fixed << setw(8) << tot_standard;
cout << "\n Total amount of hybrid vehicle commissions =$ " << fixed << setw(8) << tot_hybrid;
cout << "\n Total amount of electric vehicle commissions =$ " << fixed << setw(8) << tot_electric;
cout << "\n Total amount of all commissions paid out =$ " << fixed << setw(8) << tot_commission;
cout << "\n";
cout << "\n " << "Sales ID " << "Car type " << "Selling price " << "Commission ";
for (r_ay = 0; r_ay < tot_count; r_ay++)
{
cout << "\n " << fixed << id_num[r_ay] << " " << setprecision(2) << car[r_ay] << " " << setw(10) << price[r_ay] << " " << setw(10) << commission[r_ay];
}
if (tot_count > 0)
{
avg_comm = (tot_commission / tot_count);
comm_s = commission[0];
comm_l = commission[0];
for (r_ay = 1; r_ay < tot_count; r_ay++)
{
if (commission[r_ay] < comm_s)
comm_s = commission[r_ay];
if (commission[r_ay] > comm_l)
comm_l = commission[r_ay];
}
void print(double largeSmallAverage);
//{
// cout << "\n ";
// cout << "\n The smallest commission computed totals =$ " << fixed << setw(10) << comm_s;
// cout << "\n The largest commission computed totals =$ " << fixed << setw(10) << comm_l;
// cout << "\n Total average of commissions computed =$ " << fixed << setw(10) << avg_comm;
//}
}
cout << "\n";
change = 1;
compare = tot_count - 1;
do
{
change = 0;
for (r_ay = 0; r_ay < compare; r_ay++)
{
if (commission[r_ay] > commission[r_ay + 1])
{
temp_car = car[r_ay];
hold_id = id_num[r_ay];
hold_price = price[r_ay];
hold_comm = commission[r_ay];
commission[r_ay] = commission[r_ay + 1];
commission[r_ay + 1] = hold_comm;
id_num[r_ay] = id_num[r_ay + 1];
id_num[r_ay + 1] = hold_id;
car[r_ay] = car[r_ay + 1];
car[r_ay + 1] = temp_car;
price[r_ay] = price[r_ay + 1];
price[r_ay + 1] = hold_price;
change = 1;
}
}
compare--;
} while ((compare > 0) && (change == 1));
cout << "\n";
cout << "\n " << "Sales ID " << "Car type " << "Selling price " << "Commission ";
for (r_ay = 0; r_ay < tot_count; r_ay++)
{
cout << "\n " << fixed << id_num[r_ay] << " " << setprecision(2) << car[r_ay] << " " << setw(10) << price[r_ay] << " " << setw(10) << commission[r_ay];
cout << "\n ";
}
system("pause");
return 0;
}
}
void dashLine()
{
cout << "\n -----------------------------------";
}
int getSalesId()
{
int id_num;
cout << "\n Please enter Employee ID: ";
cin >> id_num;
while (id_num < 10000 || id_num > 99999)
{
cout << "\n Invalid Employee ID, Please enter a 5 digit ID ";
cin >> id_num;
}
return id_num;
}
int runProgram()
{
int rp_yesno;
cout << "\n Is there a customer? 1 = yes, 0 = no ";
cin >> rp_yesno;
while ((rp_yesno != 1) && (rp_yesno != 0))
{
cout << "\n Invalid Entry Please enter 1/0 ";
cout << "\n Is there a customer? 1 = yes 0 = no ";
cin >> rp_yesno;
}
return rp_yesno;
}
char vehicleType()
{
char car;
cout << "\n Please enter type of vehicle sold";
cout << "\n (S=standard, H=hybrid, E=electric): ";
cin >> car;
while (!((car == 'S') || (car == 's') || (car == 'h') || (car == 'H') || (car == 'E') || (car == 'e')))
{
cout << "\n Invalid input Please enter S/E/H ";
cin >> car;
}
return car;
}
double sellingPrice()
{
double price;
cout << "\n Please enter the selling price of the car:$ " << fixed << setprecision(2);
cin >> price;
while (price < 1)
{
cout << "\n Invalid entry, Please enter an amount greater than 0 ";
cin >> price;
}
return price;
}
void print(double largeSmallAverage)
{
double comm_s,
comm_l,
avg_comm;
{
cout << "\n ";
cout << "\n The smallest commission computed totals =$ " << fixed << setw(10) << comm_s;
cout << "\n The largest commission computed totals =$ " << fixed << setw(10) << comm_l;
cout << "\n Total average of commissions computed =$ " << fixed << setw(10) << avg_comm;
}
}
You would have a function called print that takes has three double parameters: void print(double small, double large, double average);.
Then later on you would call it with print(comm_s, comm_l, avg_comm);.
You need to change the definition of print:
void print(double small, double large, double average)
{
cout << "\n ";
cout << "\n The smallest commission computed totals =$ " << fixed << setw(10) << small;
cout << "\n The largest commission computed totals =$ " << fixed << setw(10) << large;
cout << "\n Total average of commissions computed =$ " << fixed << setw(10) << average;
}

Password count help

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