I'm trying to complete an assignment but I'm having difficulty with the math expressions and variables in general. I'm trying to make a program that takes user info on groceries and then outputs a receipt. Here is my code.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//user input
string firstItem, secondItem;
float firstPrice, secondPrice;
int firstCount, secondCount;
double salesTax = 0.08675;
double firstExt = firstPrice * firstCount;
double secondExt = secondPrice * secondCount;
double subTotal = firstExt + secondExt;
double tax = subTotal * salesTax;
double total = tax + subTotal;
//user input
cout << "What is the first item you are buying?" << endl;
getline(cin, firstItem);
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
cin.ignore();
cout << "What is the second item you are buying?" << endl;
getline(cin, secondItem);
cout << "what is the price of the " << secondItem << "?" << endl;
cin >> secondPrice;
cout << "How many " << secondItem << "s?" << endl;
cin >> secondCount;
// receipt output
cout << "1st extended price: " << firstExt << endl;
cout << "2nd extended price: " << secondExt << endl;
cout << "subtotal: " << subTotal << endl;
cout << "tax: " << tax << endl;
cout << "total: " << total << endl;
return 0;
}
The program output either 0 for all or negatives.
Your calculations must go after you read in the values, not before. You're making your calculations based on uninitialized variables.
A declaration and initialisation like
double firstExt = firstPrice * firstCount;
initialises firstExt to be the product of the current values AT THAT POINT of firstPrice and firstCount.
It doesn't set up some magic so that the value of firstExt is recalculated whenever the values of firstPrice or firstCount are changed.
In your case, firstPrice and firstCount are uninitialised variables when you do this. Accessing values of uninitialised variables of type int gives undefined behaviour.
What you need to do is something like
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
firstExt = firstPrice*firstCount; // do the calculation here
If the value of firstExt is not needed until this point, you can declare it here instead;
double firstExt = firstPrice*firstCount; // do the calculation here
which means any earlier use of firstExt will give a compiler diagnostic.
I was reading the chapter on structures in my book, and it got me re-modifying a program I already made, but this time using structures which I have never used before; however, after finishing the program, there's one issue I'm not understanding. The output of the program only displays once. It's in a for loop, and yet even though it asks me to input my information three times, it only outputs the first information.
I'm probably just not understanding how arrays in structures work.
An example of my issue is the following.
I have my output on the following loop
for(int counter = 0; counter <size; counter++)
The size is 3, which would mean I'll get the output printed three times; however the answer I'm getting is the same as if I was asking for the following.
Listofnames[0].F_name
When what I actually want is
Listofnames[0].F_name Listofnames[1].F_name Listofnames[2].F_name
However, I don't want to have to write it three times, I did to test it and it actually worked, but is that the only way to do it? Or did I miss something in my program?
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
struct Names
{
string F_name; //Creating structure called Names.
string L_name;
char Mi;
};
struct Payrate
{
double rate;
double hoursworked; //Creating structure called Payrate.
double gross;
double net;
};
int main()
{
double stateTax = 0, federalTax = 0, unionFees = 0, timeHalf = 1.5; //Initializing variables.
const int size = 2; //Array size.
Payrate employee[size]; //Structure variables
Names Listofnames[size];
for (int counter = 0; counter < size; counter++) //Initializing for loop.
{
cout << "What's your first name?: " << endl;
cin >> Listofnames[counter].F_name;
cout << "What's your last name?: " << endl; //Displaying names, and hours worked, rate.
cin >> Listofnames[counter].L_name;
cout << "What is your middle initial?: " << endl;
cin >> Listofnames[counter].Mi;
cout << "How many hours did you work? Please enter a number between 1-50: " << endl;
cin >> employee[counter].hoursworked;
cout << "What is your hourly rate? Please enter a number between 1-50: " << endl;
cin >> employee[counter].rate;
if (employee[counter].hoursworked < 0 || employee[counter].hoursworked >50) //Initializing conditional statements.
{
cout << "Sorry you entered a erong entry. Pc shutting off " << endl; //Displays what happens is user inputs a number under 0 or over 50.
}
if (employee[counter].rate < 0 || employee[counter].rate > 50) //Initializing conditional statements.
{
cout << "Sorry you entered a erong entry. Pc shutting off " << endl; //Displays what happens is user inputs a number under 0 or over 50.
}
if (employee[counter].hoursworked <= 40) //Initializing conditional statements.
{
employee[counter].gross = employee[counter].hoursworked * employee[counter].rate; //Calculating gross.
}
else if (employee[counter].hoursworked > 40) //Initializing conditional statements.
{
employee[counter].gross = employee[counter].hoursworked * (employee[counter].rate * timeHalf); //Calculating gross.
}
stateTax = employee[counter].gross * 0.06;
federalTax = employee[counter].gross * 0.12; //Calculates all the tax fees, and net.
unionFees = employee[counter].gross * 0.02;
employee[counter].net = employee[counter].gross - (stateTax + federalTax + unionFees);
}
cout << "FirstN " << "MI " << "LastName " << "\t" << "Rate " << "HoursWorked " << "TimeHalf " << "StateTax " << "FederalTax " << "UnionFees " << "Gross " << " " << "Net " << endl; //Displays header of output.
cout << "==================================================================================================================" << endl;
for (int counter = 0; counter <= size; counter++)
{
//Output.
cout << Listofnames[counter].F_name << "\t" << fixed << setprecision(2) << Listofnames[counter].Mi << " " << Listofnames[counter].L_name << "\t" << employee[counter].rate << "\t" << employee[counter].hoursworked << "\t" << setw(7) << timeHalf << "\t" << setw(8) << stateTax << setw(12) << federalTax << "\t" << unionFees << "\t" << employee[counter].gross << "\t" << employee[counter].net << endl;
system("pause");
}
}
P.s If you had to re modify this program again, what would you use to simplify it. Asking so I can keep re-modifying, and learn more advanced stuff. Vectors, pointers? Thanks in advance.
You have an array with 3 indexes but your loop is only going upto 2 indexes. Change your for loop to this.
for (int counter = 0; counter <= size; counter++)
Now, this loop will print the all the indexes.
Instead of using a static value you can also use this.
for (int counter = 0; counter < sizeof(Listofnames)/sizeof(Listofnames[0]); counter++)
sizeof(Listofnames)/sizeof(Listofnames[0]) This will give you the total size of your array.
Ideone Link
Okay so I have a calorie calculator that is supposed to be separated into the five functions including main seen below. My issue is that I get a compiler error because the variables from the inputNumber function and calculateCalories function cannot be read by any of the other functions once they are obtained. I am not allowed to use Global variables. There must be something I am missing to be able to read the variables within the main function then output them into the other functions to get the proper output. Any help would be appreciated.
Here is the code as it stands:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
int Lbs, hourr, hourW, hourWe, hourb;
double calBad, calRun, calWal, calWei;
string name;
cout << "Welcome to Megan McCracken's Workout Calculator!" << endl;
cout << endl;
cout << "Please enter your name: ";
getline(cin, name);
inputNumber(Lbs, hourr, hourW, hourWe, hourb);
calculateCalories(Lbs,hourr,hourb,hourW,hourWe,calBad,calRun,calWal,calWei);
displayHeadings(name);
displayLine(hourr,hourb,hourW,hourWe,calBad,calRun,calWal,calWei);
system("pause");
return 0;
}
int inputNumber(int Lbs, int hourr, int hourb, int hourW, int hourWe)
{
cout << "Please enter your weight: ";
cin >> Lbs;
return Lbs;
cout << "Please enter the minutes spent playing badminton: ";
cin >> hourb;
return hourb;
cout << "Please enter the minutes spent running: ";
cin >> hourr;
return hourr;
cout << "Please enter the minutes spent walking: ";
cin >> hourW;
return hourW;
cout << "Please enter the minutes spent lifting weights: ";
cin >> hourWe;
return hourWe;
cout << endl;
}
double calculateCalories(int Lbs, int hourW, int hourb, int hourr, int hourWe, double calBad, double calRun, double calWal, double calWei)
{
const double Badburn = .044, Runburn = .087, Walkb = .036, Weightb = .042;
double calBad, calRun, calWal, calWei;
calBad = (Badburn * Lbs) * hourb;
calRun = (Runburn * Lbs) * hourr;
calWal = (Walkb * Lbs) * hourW;
calWei = (Weightb * Lbs) * hourWe;
return calBad;
return calRun;
return calWal;
return calWei;
}
void displayHeadings(string name)
{
cout << "Here are the results for " << name << ": " << endl;
cout << endl;
cout << "Activity" << right << setw(18) << "Time" << right << setw(10) << "Calories" << endl;
cout << "--------------------------------------" << endl;
}
void displayLine(int hourb,int hourr, int hourW, int hourWe, double calBad, double calRun, double calWal, double calWei)
{
int HB, MB, HR, MR, HW, MW, HWE, MWE, Hour, Min;
double Calorie;
HB = (hourb / 60);
MB = (hourb % 60);
HR = (hourr / 60);
MR = (hourr % 60);
HW = (hourW / 60);
MW = (hourW % 60);
HWE = (hourWe / 60);
MWE = (hourWe % 60);
Calorie = calBad + calRun + calWal + calWei;
Hour = (hourb + hourr + hourW + hourWe) / 60;
Min = (hourb + hourr + hourW + hourWe) % 60;
cout << "Badminton" << right << setw(14) << HB << ":" << setfill('0') << setw(2) << MB << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calBad << endl;
cout << resetiosflags(ios::fixed | ios::showpoint);
cout << "Running" << right << setw(16) << HR << ":" << setfill('0') << setw(2) << MR << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calRun << endl;
cout << resetiosflags(ios::fixed | ios::showpoint);
cout << "Walking" << right << setw(16) << HW << ":" << setfill('0') << setw(2) << MW << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calWal << endl;
cout << resetiosflags(ios::fixed | ios::showpoint);
cout << "Weights" << right << setw(16) << HWE << ":" << setfill('0') << setw(2) << MWE << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << calWei << endl;
cout << "--------------------------------------" << endl;
cout << resetiosflags(ios::fixed | ios::showpoint);
cout << "Totals" << right << setw(17) << Hour << ":" << setfill('0') << setw(2) << Min << setfill(' ') << right << setw(10) << setprecision(3) << fixed << showpoint << Calorie << endl;
cout << endl;
}
If you want to modify passed-in variables within a function in C++, you should be passing them in by reference (default is by value, meaning you get a copy of the variable which is effectively thrown away when the function exits).
So, by way of example:
void xyzzy (int plugh) { plugh = 42; }
int main() {
int twisty = 7;
xyzzy (twisty);
cout << twisty << '\n';
return 0;
}
will output 7 because twisty was passed by value and changes to it within the function will not be echoed back to the caller.
However, if you pass by reference with:
void xyzzy (int &plugh) { plugh = 42; }
// ^
// This does the trick.
then you'll find it outputs 42 as desired.
For your particular case, you want to look at the variables in the argument list of inputNumber:
int inputNumber(int Lbs, int hourr, int hourb, int hourW, int hourWe)
Any of these that you want echoed back to the caller (and that looks like all of them from a cursory glance) should be pass by reference rather than pass by value.
You should also look into calculateCalories as well, since that is doing the same thing. Keep in mind that only the ones you want to change and echo back to the caller need to be pass-by-reference. So that's only the ones starting with cal.
And, since you're using the pass-by-reference to modify the variables, there's absolutely no reason to return anything from that function so it can be specified as void calculateCalories ... and the return statements removed (in any case, only the first return would have actually done anything, the others would have been unreachable code).
If you haven't yet got to the point where you can use references in your classwork (as seems to be indicated by one of your comments), you can do what C coders have been doing for decades, emulating pass-by-reference with pointers. In terms of the simplified example above, that would mean modifying the function to receive a pointer to the item you want changed, changing what it points to, and calling it with the address of the variable to be changed:
void xyzzy (int *pPlugh) { *pPlugh = 42; }
int main() {
int twisty = 7;
xyzzy (&twisty);
cout << twisty << '\n';
return 0;
}
However, it's a poor substitute for the real thing and, if your educator is trying to teach you that, it's the same as if they're getting you to use printf/scanf rather than cout/cin for user I/O: it's certainly possible in C++ since the language includes legacy C stuff, but it's not really teaching you the C++ way.
People who claim to be C++ developers but really code in C using a C++ compiler, are a rather strange breed that I like to call C+ developers - they've never really embraced the language properly. The sooner people put aside the legacy stuff, the better they'll be as C++ developers.
Pass the variables by references. Then the functions will be able to edit them.
Your other solution (not so much of a good idea but still working) is to create a struct/class and make the functions return it.
P.S. Your code won't work if the functions are in this order unless you add their signatures in the beginning:
int main();
int inputNumber(int,int,int,int,int);
//and so on
In input number, you can not use 'return' to return each value - it will do the first return statement.
In C++ you can use pass by reference so that values assigned to the variables will be passed back up.
In this case, via the input variables would be inputNumber so use '&' to denote the vaiables are references:
void inputNumber(int &Lbs, int &hourr, int &hourb, int &hourW, int &hourWe)
{
.
.
.
}
Similar idea for calculateCalories, get rid of the returns:
void calculateCalories(int Lbs, int hourW, int hourb, int hourr, int hourWe, double &calBad, double &calRun, double &calWal, double &calWei)
{
.
.
}
Note that we are only bothering to pass to reference for the variables that we will be passing back.
How do you check for non-numeric input using C++? I am using cin to read in a float value, and I want to check if non-numerical input is entered via stdin. I have tried to use scanf using the %d designator, but my output was corrupted. When using cin, I get the correct format, but when I enter, a string such as "dsffsw", I get an infinite loop.
The commented code was my attempt to capture the float, and type cast it as string, and check if it is a valid float, but the check always comes up false.
I have tried using other methods I have found on the message boards, but they want to use scanf in C and not cin in C++. How do you do this in C++? Or in C if it is not feasible.
while (!flag) {
cout << "Enter amount:" << endl;
cin >> amount;
cout << "BEGIN The amount you entered is: " << strtod(&end,&pend) << endl;
//if (!strtod(((const char *)&amount), NULL)) {
// cout << "This is not a float!" << endl;
// cout << "i = " << strtod(((const char *)&amount), NULL) << endl;
// //amount = 0.0;
//}
change = (int) ceil(amount * 100);
cout << "change = " << change << endl;
cout << "100s= " << change/100 << endl;
change %= 100;
cout << "25s= " << change/25 << endl;
change %= 25;
cout << "10s= " << change/10 << endl;
change %= 10;
cout << "5s= " << change/5 << endl;
change %= 5;
cout << "1s= " << change << endl;
cout << "END The amount you entered is: " << amount << endl;
}
return 0;
}
int amount;
cout << "Enter amount:" << endl;
while(!(cin >> amount)) {
string garbage;
cin.clear();
getline(cin,garbage);
cout << "Invalid amount. "
<< "Enter Numeric value for amount:" << endl;
}
I think you task relates to the so called defensive programming, one of it`s ideas is to prevent situations like one you described (function expects one type and user enters another).
I offer you to judge whether input is correct using method that returns stream state , which is good(),
so I think it will look something like this:
int amount = 0;
while (cin.good()) {
cout << "Enter amount:" << endl;
cin >> amount;
so i made a DOS program however my game always crashes on my second time running to the cin function.
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
//call functions
int create_enemyHP (int a);
int create_enemyAtk (int a);
int find_Enemy(int a);
int create_enemyDef (int a);
// user information
int userHP = 100;
int userAtk = 10;
int userDef = 5;
string userName;
//enemy Information
int enemyHP;
int enemyAtk;
int enemyDef;
string enemies[] = {"Raider", "Bandit", "Mugger"};
int sizeOfEnemies = sizeof(enemies) / sizeof(int);
string currentEnemy;
int chooseEnemy;
// ACTIONS
int journey;
int test;
int main()
{
// main menu
cout << "welcome brave knight, what is your name? " ;
cin >> userName;
cout << "welcome " << userName << " to Darland" << endl;
//TRAVELING
MENU:
cout << "where would you like to travel? " << endl;
cout << endl << " 1.> Theives Pass " << endl;
cout << " 2.> Humble Town " << endl;
cout << " 3.> Mission HQ " << endl;
cin >> journey;
if (journey == 1)
{
// action variable;
string c_action;
cout << "beware your journey grows dangerous " << endl;
//begins battle
// Creating the enemy, HP ATK DEF AND TYPE. ;
srand(time(0));
enemyHP = create_enemyHP(userHP);
enemyAtk = create_enemyAtk(userAtk);
enemyDef = create_enemyDef(userDef);
chooseEnemy = find_Enemy(sizeOfEnemies);
currentEnemy = enemies[chooseEnemy];
cout << " Here comes a " << currentEnemy << endl;
cout << "stats: " << endl;
cout << "HP :" << enemyHP << endl;
cout << "Attack : " << enemyAtk << endl;
cout << "Defense : " << enemyDef << endl;
ACTIONS:
cout << "Attack <A> | Defend <D> | Items <I>";
cin >> c_action;
//if ATTACK/DEFEND/ITEMS choice
if (c_action == "A" || c_action == "a"){
enemyHP = enemyHP - userAtk;
cout << " you attack the enemy reducing his health to " << enemyHP << endl;
userHP = userHP - enemyAtk;
cout << "however he lashes back causing you to have " << userHP << "health left " << endl;
//end of ATTACK ACTION
}
the last line "cin >> c_action crashes. i use two other pages. they just create the functions. is it a complier issue. also why does my complier always shutdown after it runs he app. is there a way to stop it?
A few hints:
I never use forward declarations of functions ( such as "int create_enemyHP (int a);" ) if I can avoid them. If you do this then there are two places in your code that must be correct for your program to work. It makes life easier if there is always a "single source of truth"
Have you run this code through the debugger? It will help you find problems much more quickly.
If your c_action variable is only intended to be a char, I'd suggest to use a char variable, rather than a string.
You might want to try this way, and if you're still faced with an error, you might give
scanf("%c", &c_action); //assuming you used a char.
I didn't understand if the program crashes before you type the "action" or after. Because if it crashes before, then I think your problems are caused by white spaces characters in the input buffer.