So this is a very simple problem I'm sure, but I'm just starting out.
In the program, there is simple input validation. If inputed is entered properly, no issues.
The problem is, when testing the program with an error, like entering a zero or negative number, all the variables are blank (i.e., strings become blank and numbers become zero) in the output.
Thanks ahead of time for the help and insight.
// This menu driven program determines the time sound will take to travel through
// gas, liquid, and solid, given a distance from a user.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
// constants
const double AIR_SPEED_RATE_PER_SECOND_SOUND = 1100.0, //in feet per second
WATER_SPEED_RATE_PER_SECOND_SOUND = 4900.0, // in feet per second
STEEL_SPEED_RATE_PER_SECOND_SOUND = 16400.0; // in feet per second
// Program defined variables
double Time_To_Travel = 0.0; // in seconds
string Medium;
// User defined variables
double distance_of_travel; //in feet
int menu_selection;
//Display a menu for mediums of sound conduction.
cout << "Sound travels at different speeds through air, water, and steel." << endl;
cout << "\nThis program will calculate the time it takes, in feet per second, for " \
"sound to travel a given distance." << endl;
cout << "Please select a number choice below:\n\n1. Air\n2. Water\n3. Steel " << endl;
//Get input from user.
cout << "\nEnter Selection: ";
cin >> menu_selection;
cout << "\nEnter distance in feet the sound will travel: ";
cin >> distance_of_travel;
// Input validate selection is on the menu
if (menu_selection >= 1 && menu_selection <= 3)
{
if (distance_of_travel > 0.0) // input validation distance is positive
{
switch (menu_selection) // calculate the time of travel based on user input
{
case 1: Medium = "air";
Time_To_Travel = distance_of_travel / AIR_SPEED_RATE_PER_SECOND_SOUND;
break;
case 2: Medium = "water";
Time_To_Travel = distance_of_travel / WATER_SPEED_RATE_PER_SECOND_SOUND;
break;
case 3: Medium = "steel";
Time_To_Travel = distance_of_travel / STEEL_SPEED_RATE_PER_SECOND_SOUND;
break;
}
}
else
{
cout << "\nPlease enter a distance greater than zero: ";
cin >> distance_of_travel;
}
}
else
{
cout << "\nMenu selection is not 1, 2, or 3.\n\nPlease correctly enter a number 1 through 3: ";
cin >> menu_selection;
}
// Format to four decimal places and display the time sound takes to travel given distance.
cout << fixed << showpoint << setprecision(4);
cout << "Sound would take " << Time_To_Travel << " seconds to travel given distance of " << distance_of_travel << " feet in " << Medium << "." << endl;;
return 0;
}
An if statement is a simple branch, not a loop. At the end of the if, execution continues past the end of the block.
if (menu_selection >= 1 && menu_selection <= 3)
This, when false, will skip the meat of your program and jump to your code that handles invalid input.
else
{
cout << "\nMenu selection is not 1, 2, or 3.\n\nPlease correctly enter a number 1 through 3: ";
cin >> menu_selection;
}
After you input menu_selection again, control flows to
cout << fixed << showpoint << setprecision(4);
cout << "Sound would take " << Time_To_Travel << " seconds to travel given distance of " << distance_of_travel << " feet in " << Medium << "." << endl;;
return 0;
The new input is never acted on, and the untouched values are printed. Replace the initial if with a do {...} while(condition); loop that wraps the user input. Once the input is satisfactory, you can then proceed to the core of the program.
bool is_good;
do
{
is_good = false;
cout << "\nEnter Selection: ";
cin >> menu_selection;
cout << "\nEnter distance in feet the sound will travel: ";
cin >> distance_of_travel;
if (menu_selection < 1 || menu_selection > 3 || distance_of_travel < 0)
cout << "error message here";
else
is_good = true;
} while (!is_good);
You can handle zero, negative number, or all possible inputs that are not defined in your case block by adding default block to your switch statement. Then your code will look like something like this.
switch (menu_selection) // calculate the time of travel based on user input
{
case 1: Medium = "air";
Time_To_Travel = distance_of_travel / AIR_SPEED_RATE_PER_SECOND_SOUND;
break;
case 2: Medium = "water";
Time_To_Travel = distance_of_travel / WATER_SPEED_RATE_PER_SECOND_SOUND;
break;
case 3: Medium = "steel";
Time_To_Travel = distance_of_travel / STEEL_SPEED_RATE_PER_SECOND_SOUND;
break;
default:
// handle zero, negative numbers and so on.
break;
}
Reference: http://www.tutorialspoint.com/cplusplus/cpp_switch_statement.htm
Related
I'm needing a little help, this program is meant to calculate and output the body weight of users vs their body weight on planets in our solar system.
When I try to use a switch statement for this program, the entire statement is marked as error specifically 'Illegal case error' and 'case label may only be used within a switch' errors .I have tried comparing my statement with others in my textbook but can find no difference. Please tell me how I can fix this.
#include <cctype>
#include <iostream>
#include <cmath>
using namespace std;
double weight;
double planet_weight;
string planet;
double weightonplanet = 0;
enum planet_names{Mercury,Venus,Earth,Moon,Mars,Jupiter,Saturn,Uranus,Neptune,Pluto};
int main()
{
cout << "********************************************************************" << endl;
cout << endl;
cout << "Enter the name of a planet from the following options:" << endl;
cout << "(Mercury,Venus,Earth,Moon, Mars,Jupiter,Saturn,Uranus,Neptune,Pluto)" << endl;
cout << endl;
cout << "********************************************************************" << endl;
cin >> planet;
cout << endl;
cout << endl;
cout << "Please enter your current weight (ex:205)" << endl;
cin >> weight;
cout << endl;
cout << "You have entered " << planet << "." << endl;
cout << "You currently weigh " << weight << "lbs." << endl;
cout << "Your weigh on " << planet << "is " << weightonplanet << " ." << endl;
while (true)
{
switch (string planet);
{
case Mercury:
weightonplanet = weight * 0.4155;
break;
case Venus:
weightonplanet = weight * 0.8975;
break;
case Earth:
weightonplanet = weight * 1.0;
break;
case Moon:
weightonplanet = weight * 0.166;
break;
case Mars:
weightonplanet = weight * 0.3507;
break;
case Jupiter:
weightonplanet = weight * 2.5374;
break;
case Saturn:
weightonplanet = weight * 1.0677;
break;
case Uranus:
weightonplanet = weight * 0.8947;
break;
case Neptune:
weightonplanet = weight * 1.1794;
break;
case Pluto :
weightonplanet = weight * 0.899;
break;
}
}
return weightonplanet;
Problem 1: Bogus semicolon.
switch (string planet);
^
remove me!
Problem 2: Can't switch on a string
The why is covered here: Why the switch statement cannot be applied on strings?
Solution
So what can we do?
We can have a chain of if-else-if statements comparing strings. Sounds ugly but for short lists, this is probably the fastest approach. Note: If you go this route, you can directly compare std::strings, so there is no need for strcmp.
if (planet == "Mercury")
{
weightonplanet = weight * 0.4155;
}
if (planet == "Venus")
{
weightonplanet = weight * 0.8975;
}
...
We can also map the planet name to the enum and then switch on the enum. But if we're going to do that, why not eliminate the enum and the switch and map the planet name directly to the planet's gravity?
To demonstrate this I'll use std::map from the C++ Standard Library.
#include <iostream>
#include <string> // added to get std::string. Sometimes you get it free from
// iostream, but you can't count on this, so leaving string
// out could be leaving a boobytrap for someone in the future
// If you use it, include it.
#include <map> // added to get std::map
using namespace std; // often dangerous. Use with caution
int main()
{
// No need for these variables to be global. Enclose them in main's scope
double weight;
string planet;
// removed a couple variables because they're not needed anymore
// you can chain <<s into one big statement. No need to line them up all nice and purty
// I just find it easier to read. Easier to read is easier to debug and maintain,
// so it worth the time spent. Your mileage may vary.
cout << "********************************************************************" << endl
<< endl
<< "Enter the name of a planet from the following options:" << endl
<< "(Mercury,Venus,Earth,Moon, Mars,Jupiter,Saturn,Uranus,Neptune,Pluto)" << endl
<< endl
<< "********************************************************************" << endl;
cin >> planet;
cout << endl
<< endl
<< "Please enter your current weight (ex:205)" << endl;
cin >> weight;
// can't switch on a string so here I'm mapping planet names to gravity
map<string, double> weightmap =
{
{ "Mercury", 0.4155 },
{ "Venus", 0.8975 },
{ "Earth", 1.0 },
{ "Moon", 0.166 }, // not a planet.
{ "Mars", 0.3507 },
{ "Jupiter", 2.5374 },
{ "Saturn", 1.0677 },
{ "Uranus", 0.8947 },
{ "Neptune", 1.1794 },
{ "Pluto", 0.899 } // not a planet.
};
// so now here we just look up the planet name in the map, and get gravity
// one multiplication later, we're done!
cout << endl
<< "You have entered " << planet << "." << endl
<< "You currently weigh " << weight << "lbs." << endl
<< "Your weight on " << planet << "is " << weight * weightmap[planet] << " ." << endl;
}
There are a few problems here. "Saturn" is not the same as "saturn". You may want to convert the user's input to lower or upper case and only test that one case.
If the user inputs a name that is not in the map, the map will create a new entry for that planet and initialize it to zero. So as far as this program is concerned, "Iscandar" has zero gravitational force. If you want to trap planets not in the map, use std::map::find. If the input is not found, ask the user to provide another input. Or mock them mercilessly and exit. Your call.
A quick note about map creating entries for you. This can be extremely useful, frequency counters of sparse items for example, but if the program will run for a long time take care that you don't fill up an ungodly amount of memory with typos.
Finally, a quick note on using namespace std;: Why is "using namespace std;" considered bad practice?
after user input you must set a countable variable(int, enum, enum class, ...)
for each string and use this variable to process on user input and i think it's bad idea.
in this case you can use 'if - else' statements.
for example
if(!strcmp(planet, "Mercury"))
{
//do your job
}
else if(!strcmp(planet, "Mars")
.
.
.
So for a program I'm writing I have a menu the user can enter an integer choice to calculate a few different things. Choice 1-4 are calculations, 5 should call a function to print data from a file to the console, and 6 quits everything. For whatever reason after adding a new case (5) to the switch statement I had, my code has kind of broken. When I enter 5 the program still asks me to enter a weight (which I don't understand at all), after which it will enter an infinite loop, which means it has to have made it into the while loop in my print() function. I don't understand what the hell is going on so I would really appreciate a second set of eyes.
int main()
{
srand(time(0));
bool repeat = true;
bool loopFlag = true;
float calories = 0;
string intensity = "";
cout << "Welcome to Carmello's Fitness Center" << endl;
do // main loop
{
fstream transactionLog;
transactionLog.open("userfile.txt", std::ios::in |std::ios::out |std::ios::app);
int idNum;
menu(idNum); // simply displays the menu
loopFlag = true;
int choice = userChoice(choice, loopFlag); // gets the users menu choice
loopFlag = true; // this resets the loopflag to ensure it can be used again after the last validation
float weight = userWeight(weight, loopFlag); // gets users weight and converts into kilograms for further calculations
float weightPoundsCopy = weight;
weight = weight / 2.2;
int time = 0;
float calories = 0;
switch (choice)
{
case 1:
{
int lower = 30, upper = 60;
int activity = BIKING;
string description = "riding the stationary bike: ";
met(weight, loopFlag, activity, lower, upper, description, time, calories, intensity);
break;
}
case 2:
{
int lower = 30, upper = 60;
int activity = RUNNING;
string description = "running on the treadmill: ";
met(weight, loopFlag, activity, lower, upper, description, time, calories, intensity);
break;
}
case 3:
{
int lower = 15, upper = 30;
int activity = LIFTING;
string description = "lifting weights: ";
met(weight, loopFlag, activity, lower, upper, description, time, calories, intensity);
break;
}
case 4:
{
int lower = 60, upper = 90;
int activity = YOGA;
string description = "doing Hatha Yoga: ";
met(weight, loopFlag, activity, lower, upper, description, time, calories, intensity);
break;
}
case 5:
{
cout << "5 CHOSEN";
print (transactionLog);
break;
}
}
cout << setfill('0') << setw(5) << idNum << endl;
cout << choice << endl;
cout << time << endl;
cout << weightPoundsCopy << endl;
cout << calories << endl;
cout << intensity << endl;
outputFunction(transactionLog, idNum, choice, time, weightPoundsCopy, calories, intensity);
transactionLog.close();
}
while (repeat);
}
Here are what seem to be the most relevant functions
int userChoice (int choice, bool loopFlag)
{
do // loop to validate user's activity (choice) input
{
cin >> choice;
if (cin.fail() || choice > 6 || choice < 1)
{
cout << "\nInvalid choice. Please choose from option 1 through 6." << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else if (choice == 6)
{
exit(EXIT_SUCCESS); // exits program if user chooses to
}
else
{
loopFlag = false;
}
}
while (loopFlag); // loop will continue until input meets correct conditions and thus sets loopflag to false
return choice;
}
and
float userWeight(float weightPounds, bool loopFlag)
{
do // this do-while loop validates weight input
{
cout << "\nPlease enter your weight in pounds: " << endl;
cin >> weightPounds;
if (cin.fail() || weightPounds <= 0 || weightPounds >= 1000)
{
cout << "\nInvalid weight entry!" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else
{
loopFlag = false;
}
}
while (loopFlag);
return weightPounds;
}
and
void print(fstream &transactionLog)
{
// reset everything and go to the beginning of the file
transactionLog.clear();
transactionLog.seekg(0, std::ios::beg);
// start the streaming >>
if (enterPassword)
{
while(!transactionLog.eof())
{
cout << setw(20) << left << "UserID" << "Activity" << "Mins" << "Weight"
<< "Calories" << "Intensity" << "Time Stamp" << endl;
}
}
else
{
cout << "SECURITY BREACH" << endl;
return;
}
}
I think your code works as it been written. You has beed asked user made his choice by calling "userChoice" function and in anyway after that you has beed asked a user weight by calling "userWeight" function. Only after that you has been parsed user input in a switch case.
If you want that your program didn't asked user weight you should written somethin like that:
if (userInput < 5)
{
weight = userWeight(weight, loopFlag);
float weightPoundsCopy = weight;
weight = weight / 2.2;
}
For a class project I have to develop a program that calculates the cost of a mobile device service. There are 3 packages the user can choose from. The cost of the service is determined by the base price and number of message units to be used. After the user chooses a package I have to let them know the price of the package as well as letting them know if either of the other packages would be cheaper and show what the difference in price would be by using switch statements. I've wrote some switch statements comparing the packages, but how do I show and calculate how much they would save if there is a cheaper package than the one chosen? I am also a beginner so take it easy.
int main() {
bool finished = false;
do {
// to keep it simple
double choice_a = 9.95;
double choice_b = 19.95;
double choice_c = 39.95;
char choice;
int message_units;
double price;
bool selected = false;
// this loop shows the options initially
do {
cout << "Which package do you choose (enter A, B or C)" << endl;
// you will need to check this
cin >> choice;
// keeping it simple
if (choice == 'A') { price = choice_a; selected = true; }
else if (choice == 'B') { price = choice_b; selected = true; }
else if (choice == 'C') { price = choice_c; selected = true; }
cout << endl;
}
// loops until something was selected
while (selected == false);
// user enters how many units is wanted
cout << "How many message units (enter 1 - 672)" << endl;
// again check this (if homework requires checking input)
cin >> message_units;
// Calculating message units
if(message_units > 5){
price += 100 * (message_units - 5);
}
if(message_units > 15){
price += 50 * (message_units - 15);
}
// Total Price Output
cout << "Your total cost is " << price/100 << endl
// Is user done?
char done;
cout << "Do you want to enter another? press enter to continue.
cin >> done;
// check
if (done != ' ') {
finished = true;
}
}
while (finished = false);
}
switch (choice)
{
case 'A':
if(choice_b < choice_a);
cout << "You can save by switching to package B" << endl;
else if(choice_c < choice_a);
cout << "You can save by switching to package C" << endl;
break;
case 'B':
if(choice_a < choice_b);
cout << "You can save by switching to package A" << endl;
else if(choice_c < choice_b);
cout << "You can save by switching to package C" << endl;
break;
case 'C':
if(choice_a < choice_c);
cout << "You can save by switching to package A" << endl;
else if(choice_b < choice_c);
cout << "You can save by switching to package B" << endl;
break;
}
#include <iostream>
using namespace std;
int main() {
bool finished = false;
char choice;
double choice_a = 9.95;
double choice_b = 19.95;
double choice_c = 39.95;
int message_units;
double price;
bool selected = false;
do {
// to keep it simple
// this loop shows the options initially
do {
cout << "Which package do you choose (enter A, B or C)" << endl;
// you will need to check this
cin >> choice;
// keeping it simple
if (choice == 'A') { price = choice_a; selected = true; }
else if (choice == 'B') { price = choice_b; selected = true; }
else if (choice == 'C') { price = choice_c; selected = true; }
cout << endl;
}
// loops until something was selected
while (selected == false);
// user enters how many units is wanted
cout << "How many message units (enter 1 - 672)" << endl;
// again check this (if homework requires checking input)
cin >> message_units;
// Calculating message units
if(message_units > 5){
price += 100 * (message_units - 5);
}
if(message_units > 15){
price += 50 * (message_units - 15);
}
// Total Price Output
cout << "Your total cost is " << price/100 << endl;
switch (choice)
{
case 'A':
if(choice_b < choice_a)
cout << "you can save by switching to package B it saves: " << choice_a - choice_b << " if you choose B" << endl;
else if(choice_c < choice_a)
cout << "You can save by switching to package C is saves: " << choice_a - choice_c << endl;
break;
case 'B':
if(choice_a < choice_b)
cout << "you can save by switching to package A it saves: " << choice_b - choice_a << " if you choose a" << endl;
else if(choice_c < choice_b)
cout << "you can save by switching to package C it saves: " << choice_b - choice_c << " if you choose c" << endl;
break;
case 'C':
if(choice_a < choice_c)
cout << "you can save by switching to package A it saves: " << choice_c - choice_a << " if you choose a" << endl;
else if(choice_b < choice_c)
cout << "you can save by switching to package A it saves: " << choice_c - choice_b << " if you choose b" << endl;
break;
}
// Is user done?
char done;
cout << "Do you want to enter another? press enter to continue.";
cin >> done;
// check
if (done != ' ') {
finished = true;
}
}
while (finished == false);
}
sorry for not explaining but i try explaining it the best i can
based on your code. i fix some wrong syntaxe and tries to match the problem
you've post so i defined all the variables you've created outside the first
outer bool so that the switch statement will work and i edit some code in the switch statement to calculate the amount of savings and displays them based on the conditions sorry for bad english.
Assuming you are comparing the two with the same quantity,
Savings = [(Selection Price) - (Cheaper Option Price)]× Quantity
If you do this calculation and say assign it to a type double called Savings, you can print this out.
cout << "Savings are "<< Savings;
Doing this on each if statement is simple, but of course there are better ways to do this. Such as calling a function that does this simple calculation for two options.
EDIT 1: Apologize for the poor formatting, this is on my phone.
EDIT 2: Also noticed you have incorrect syntax with your control loops. Here is a good resource here
EDIT 3: There are actually a number of other issues including your switch statement being outside of main.
This line doesn't make sense, in practical terms.
// Calculating message units if(message_units > 5){ price += 100 * (message_units - 5); } if(message_units > 15){ price += 50 * (message_units - 15); }
Good practice would suggest not overwriting a variable with a value with a different meaning. It is confusing. Initially it seems price is the per quantity price. Then it looks like you try to assign the overall cost to it.
(I'm assuming; it doesn't actually do this. Instead it adds a price of 100 per unit except for the first 5 to a single unit price you declare at the top. Similarly for the greater than 15 block.)
EDIT 4: Per request in comments:
If I am correct in what I think you are trying to do, replace this block:
// Calculating message units
if(message_units > 5){
price += 100 * (message_units - 5);
}
if(message_units > 15){
price += 50 * (message_units - 15);
}
with:
double Total_Cost;
if(message_units => 5 && message_units<15){
Total_Cost = price * (message_units - 5);
}
else if(message_units => 15){
Total_Cost = price * (message_units - 15);
}
else{
Total_Cost = price * message_units;
}
That is 'you get the first 5 free (or 15) if you buy in bulk'. Otherwise it is just the price times the number of units. This again seems kind of strange, but this is what this does.
I have these block of codes that belong to a NIM subtraction game. The thing that I would like to implement is that user is going to be able play the game as long as he/she wants. Simply if user enters 999 program will exit, otherwise user will be playing until he/she enters 999. Here is my block of codes. I am not sure that I make a logical mistake or I need to add some specific exit code. Thanks for your time and attention.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int total, n;
while(true){
cout << "Welcome to NIM. \nEnter 999 to quit the game!\nPick a starting total: ";
cin >> total;
if(total==999)
break;
while(true){
//pick best response and print results.
if ((total % 3) == 2)
{
total = total - 2;
cout << "I am subtracting 2." << endl;
}
else
{
total--;
cout << "I am subtracting 1." << endl;
}
cout << "New total is " << total << endl;
if (total == 0)
{
cout << "I win!" << endl;
break;
}
// Get user’s response; must be 1 or 2.
cout << "Enter num to subtract (1 or 2): ";
cin >> n;
while (n < 1 || n > 2)
{
cout << "Input must be 1 or 2." << endl;
cout << "Re-enter: ";
cin >> n;
}
total = total - n;
cout << "New total is " << total << endl;
if (total == 0)
{
cout << "You win!" << endl;
break;
}
}
}
return 0;
}
You are modifying total inside the loop. Just test after cin>>total at the beginning if total==999 and break if true, i.e.
if(total==999)
break;
and replace the do-while loop by a while(true){}
In the do-while loop you are trying to compare character literal '999' with variable total that has type int.
}while(total!='999');
Though this code is valid its result can be something else than you are expecting. Values of character literals with more than one symbol are implementation defined.
You have to write
} while ( total != 999 );
Also if the player will enter 999 you start to play with him though you have to exit the game.
So in my opinion it is better to use while loop. For example
while ( true )
{
cout << "Welcome to NIM. \nEnter 999 to quit the game!\nPick a starting total: ";
cin >> total;
if ( total == 999 ) break;
// ...
}
you have to do three corrections in your code to make it right
first you have to check if total is equal to 999, then break in your do loop just after getting the total from user
second - you have to put same condition in your first while loop
and lastly - instead of while(total!='999') u shall write while(total!=999) because it is integer
How to input a string of charaters like "Peter Johnson"?
My program only reads 1 single name, if I put a space, the program loops infinitely
Writting John, works, but the space character makes it loop. Why is that? Also I know the program might not be completely finished.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int x=0;
char name [25];
float paycheck;
cout<<"WELCOME TO THE EMPLOYEE SALARY GENERATION PROGRAM\n\n";
while (x!=-1)
{
cout<<"Enter employee name or -1 to stop the program\n";
cin>>name;
cout<<"Enter employee code (1=manager, 2=worker, 3=comission, 4=pieceworker) or -1 to stop the program\n";
cin>>x;
switch (x)
{
case 1:
cout<<"Your weekly total paycheck is 2 500 $\n"; // FIXED weekly manager's salary
break;
case 2: // 8.50 per hour + over time for workers
cout<<"Please enter the amount of hours worked\n";
cin>>paycheck;
if(paycheck<40)
paycheck=paycheck*8.50;
else
paycheck= (paycheck-40)*8.50 +(40*8.50);
cout<<name<<"'s paycheck is "<<paycheck<<"$\n";
break;
case 3: // comission workers make 250 + 5.7% of their weekly sales
cout<<"Please enter amount of weekly sale made\n";
cin>>paycheck;
paycheck = paycheck*5.7/100 + 250;
break;
case 4: // pieceworkers make 50$ per item produced
cout<<"Please enter the number of items produced this week\n";
cin>>paycheck;
paycheck = paycheck*50;
cout<<"The employee"<<name<<"Made"<<paycheck<<"$ this week";
break;
default:
break;
}
}
system ("PAUSE");
}
The 'cin' function stops reading when it finds a space. Use 'getline' to read the names.
EDIT: Debug the code, and added some safe measures to avoid program crashing due to bad input.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
float foo()
{
float fl = 0.0f;
string str;
while(true) {
getline(cin, str);
stringstream sstream(str);
if (sstream >> fl)
break;
cout << "Invalid Input" << endl;
}
return fl;
}
int main()
{
string x;
string name;
char number = {0};
float paycheck;
cout << "WELCOME TO THE EMPLOYEE SALARY GENERATION PROGRAM" << endl << endl;
while (x!="-1") {
cout << "Enter employee name or -1 to stop the program" << endl;
getline(cin, name);
if (name == "-1") return 0;
cout<<"Enter employee code (1=manager, 2=worker, 3=comission, 4=pieceworker) or -1 to stop the program\n";
getline(cin, x);
if (x == "-1") return 0;
if (x.length() == 1)
number = x[0];
else {
cout << "Invalid Input" << endl;
continue;
}
switch (number) {
case '1':
cout << "Your weekly total paycheck is 2 500 $" << endl; // FIXED weekly manager's salary
break;
case '2': // 8.50 per hour + over time for workers
cout << "Please enter the amount of hours worked" << endl;
paycheck = foo();
if(paycheck<40)
paycheck=paycheck*8.50;
else
paycheck= (paycheck-40)*8.50 +(40*8.50);
cout << name << "'s paycheck is " << paycheck << "$" << endl;
break;
case '3': // comission workers make 250 + 5.7% of their weekly sales
cout << "Please enter amount of weekly sale made" << endl;
paycheck = foo();
paycheck = paycheck*5.7/100 + 250;
break;
case '4': // pieceworkers make 50$ per item produced
cout<<"Please enter the number of items produced this week" << endl;
paycheck = foo();
paycheck = paycheck*50;
cout<<"The employee " << name << " Made "<< paycheck << "$ this week" << endl;
break;
default:
cout << "Invalid Option." << endl;
break;
}
}
system ("PAUSE");
}
The main lesson to take away from this is: always check after reading that the read was successful! It wasn't don't proceed. In general, input looks something like this:
if (in >> var1 >> var2) { ... }
if (std::getline(in, string)) { ... }
... you'd use the input in the condition of a loop. Your main problems seem that the input for strings using in >> s first skips leading spaces and then reads non-space characters up to the first space (where space actually is any whitespace like space, newline, carriage return, form feed, backspace, etc.). If you want to read multiple words you'd need to determine how to best tell that reading should stop. For example you could read up to a specific character using std::getline(in, s, c) (where c defaults to \n if omitted).
If you try to read a value which can't be parsed successfully, e.g. when trying to read a number when the next non-space character isn't a digit, the stream will go into fail stated (i.e. its state gets the std::ios_base::failbit set) and it won't do anything useful until the state is clear()ed.
Use std::string
std::string myName;
std::getline(std::cin, myName);