I am in a beginner C++ course. Here are the instructions for my assignment:
Write a program that calls a value-returning function that prompts the user to enter the weight of a person in pounds and then calls another value returning function to calculate the equivalent weight in kilograms. Output both the weights rounded to two decimal places. (Note that 1 kilogram = 2.2 pounds.) Format your output with two decimal places.
I thought everything was perfect. However, I am a getting a debug error, which is Runtime Check Error #3 - T. Please review my code and tell me what is wrong here. Remember, I am a beginner. Thank you.
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
string get_date();
void student_heading();
float get_user_input(float);
float convert_weight(float);
int main()
{
cout << fixed << showpoint << setprecision(2);
string mydate;
float weight_lbs;
float weight_kgs;
mydate = get_date();
student_heading();
weight_lbs = get_user_input();
weight_kgs = convert_weight(weight_lbs);
return 0;
}
string get_date()
{
string mydate;
cout << "Enter today's date:";
getline(cin, mydate);
return mydate;
}
void student_heading()
{
cout << "*******************" << endl;
cout << "Student" << endl;
cout << "ID Number" << endl;
cout << "SYCS-135" << endl;
cout << "Assignment 6" << endl;
cout << "October 6, 2015" << endl;
cout << "******************" << endl;
}
float get_user_input(float lb_weight)
{
cout << "Please provide us with your weight, in pounds:";
cin >> lb_weight;
return lb_weight;
}
float convert_weight(float kg_weight)
{
float lb_weight;
kg_weight = lb_weight / 2.2;
return kg_weight;
}
Your error is that you are calling weight_lbs = get_user_input();
You cant call get_user_input with no argument because you do not have any function like that.
Your code has several issues.
Your function prototypes are not correct. The parameter in the braces have to contain the variable name as well as data type. So only function(int) is not enaugh, it should be function(int MyVariable). So the error was caused by calling function, which didn't exist, because your function prototype was not correct (expected a parameter).
Your get_user_input() function has a parameter which is not needed. The whole function should look like this:
float get_user_input()
{
cout << "Please provide us with your weight, in pounds:";
float lb_weight;
cin >> lb_weight;
return lb_weight;
}
Function for mass conversion can look like this:
float convert_weight(float lb_weight)
{
return lb_weight / 2.2;
}
Your main function then should look like this:
int main()
{
cout << fixed << showpoint << setprecision(2);
string mydate;
float weight_lbs;
float weight_kgs;
mydate = get_date();
cout << mydate << endl;
student_heading();
weight_lbs = get_user_input();
weight_kgs = convert_weight(weight_lbs);
cout << weight_kgs << "Kg";
getchar();
getchar();
return 0;
}
Don't forget to change the function prototypes to:
float get_user_input();
float convert_weight(float lb_weight);
Related
I'm working on a project for my "Programming I" class, and I am getting a strange error. It's a payroll program that calculates taxes and what-not, and our professor wants us to put some of our functions in separate .cpp files.
I've set it up so that each employee is treated as a struct:
#include <string>
using namespace std;
struct Employee {
string firstName;
string lastName;
string name;
double rate;
double hours;
char status;
double grossPay;
double insurance;
double socialSecurity;
double stateTax;
double federalTax;
double PYE;
double netPay;
};
In my main program, I have an array of seven employees: "employees", and initialize it from a separate text file, but when I try to pass the array to one of my functions in the separate .cpp files, I get this error:
argument of type "Employee *" is incompatible with parameter of type "Employee *"
The thing is, though that only happens on the first two out of three functions, while the third is fine even when commenting out the first two:
int main() {
const int numEmployees = 7;
Employee employees[numEmployees];
cout << "name" << setw(20) << right << "rate" << setw(8) << "hours" << setw(7) << "ins" << setw(7) << "soc" << setw(7) << "state" << setw(7) << "fed" << setw(7) << "net" << endl
<< setw(46) << "sec" << setw(6) << "tax" << setw(8) << "tax" << endl;
fstream data("employees.txt");
for (int i = 0; i < numEmployees; i++) {
data >> employees[i].firstName >> employees[i].lastName >> employees[i].rate >> employees[i].hours >> employees[i].status;
employees[i].name = employees[i].firstName + " " + employees[i].lastName;
}
computeGrossPay(employees, numEmployees); //<-\
computeInsurance(employees, numEmployees); //<- these two are errors
computeFederalTax(employees, numEmployees); //<-- this one is fine
for (int i = 0; i < numEmployees; i++) {
// compute social security withheld as 7% of gross pay
employees[i].socialSecurity = employees[i].grossPay * 0.07;
// compute state tax as 3% of gross pay
employees[i].stateTax = employees[i].grossPay * 0.03;
// Compute PYE (Projected Yearly earnings) as gross-pay times 52.
employees[i].PYE = employees[i].grossPay * 52;
// Compute Net pay as gross-pay minus insurance minus soc-sec minus state-tax minus fed-tax
employees[i].netPay = employees[i].grossPay - employees[i].insurance - employees[i].socialSecurity - employees[i].stateTax - employees[i].federalTax;
}
printPayroll(employees, numEmployees);
}
Here are what each of the functions look like, each in their own separate file:
void computeGrossPay(Employee* employees, int numEmployees) {
// do stuff
}
void computeInsurance(Employee* employees, int numEmployees) {
// do stuff
}
void computeFederalTax(Employee* employees, int numEmployees) {
// do stuff
}
How can I fix this?
EDIT: I believe this may have been a problem with my IDE. I was using Visual Studio, and as other users pointed out, it compiles just fine elsewhere. I think I'll stick to basic text editors until I'm ready for the more advanced IDEs.
I have several remarks about this code. This code is using C-style arrays, and passing it as pointers and pointer size, which is ill-advised. Also, It doesn't use some of the most basic concepts of C++.
I have made some rearrangements - mostly made Employee into a real struct/class, with its own member functions, instead of passing it from outside. Made the array using the std::array (which is preferable over the raw array), and finally, a small touch - made the number of employees a constexpr.
I haven't arranged the input parsing, but actually, Employee needs to be a class, that disallows touching the values of its members from outside, and should have a constructor, which gets all the relevant inputs, instead of what is done now.
Look at this rearranged code:
using namespace std; // I strongly suggest against it!!!!
struct Employee {
string firstName;
string lastName;
string name;
double rate;
double hours;
char status;
double grossPay;
double insurance;
double socialSecurity;
double stateTax;
double federalTax;
double PYE;
double netPay;
void computeAll() // a bad name, but I don't have a better idea now!
{
computeGrossPay();
computeInsurance();
computeFederalTax();
computeSocialSecurity();
computeStateTax();
computePYE();
computeNetPay();
}
private:
void computeGrossPay();
void computeInsurance();
void computeFederalTax();
void computeSocialSecurity();
void computeStateTax();
void computePYE();
void computeNetPay();
};
int main() {
constexpr uint64_t NUM_OF_EMPLOYEES = 7;
std::array<Employee, NUM_OF_EMPLOYEES> employees{};
cout << "name" << setw(20) << right << "rate" << setw(8) << "hours" << setw(7) << "ins" << setw(7) << "soc" << setw(7) << "state" << setw(7) << "fed" << setw(7) << "net" << endl
<< setw(46) << "sec" << setw(6) << "tax" << setw(8) << "tax" << endl;
fstream data("employees.txt");
for (auto& employee : employees)
{
data >> employee.firstName >> employee.lastName >> employee.rate >> employee.hours >> employee.status;
employee.name = employee.firstName + " " + employee.lastName;
employee.computeAll();
}
return 0;
}
This is an assignment for a course that I am having problems with. Until now I thought I was fairly familiar with vectors in C++. This program is supposed to take a file from the user calculate the users pay then spit back out in a nice table all the information relevant.
It must contain a vector of struct and I must use push_back. I get two errors that I cannot figure out at this moment. In the for loop at the end of main() it tells me a reference type of vector cannot be initialized with Employee. The two functions after ward tell me that I for example .HoursWorked is not a member of the struct.
I tried looking around other questions for help but they all mentioned not using pointers which I'm 100% positive there are no pointers in my program. The txt file I am using for testing the program looks as follows:
John Smith 123-09-8765 9.00 46 F
Kevin Ashes 321-09-8444 9.50 40 F
Kim Cares 131-12-1231 11.25 50 P
Trish Dish 141-51-4564 7.52 24 P
Kyle Wader 432-12-9889 5.75 48 F
Code:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <vector>
using namespace std;
struct Employee
{
string name;
string ssn;
double hourlyWage;
double HoursWorked;
char status;
double straightTimePay;
double overTimePay;
double netPay;
};
void calculatePay(vector<Employee>& buisness);
void displayEmployee(vector<Employee> buisness);
int main()
{
vector<Employee> buisness;
string fileName, line;
ifstream inFile;
stringstream ss;
cout << "Please input the file name to read: ";
cin >> fileName;
inFile.open(fileName);
if (!inFile)
{
cout << "Cannot open file " << fileName << " Aborting!" << endl;
exit(1);
}
int index = 0;
string firstName, lastName;
getline(inFile, line);
while (!inFile.eof())
{
if (line.length() > 0)
{
ss.clear();
ss.str(line);
buisness.push_back;
ss >> firstName >> lastName;
buisness[index].name = firstName + " " + lastName;
ss >> buisness[index].ssn;
ss >> buisness[index].hourlyWage >> buisness[index].HoursWorked;
ss >> buisness[index].status;
index++;
}
getline(inFile, line);
}
inFile.close();
cout << "The information of the buisness:" << endl;
cout << setw(20) << "Name" << setw(15) << "SSN" << setw(12) << "Hourly Wage";
cout << setw(14) << "Hours Worked" << setw(18) << "Straight Time Pay";
cout << setw(14) << "Over Time Pay" << setw(6) << "Status" << setw(10) << "Net Pay" << endl;
for (index = 0; index < buisness.size(); index++)
{
calculatePay(buisness[index]);
displayEmployee(buisness[index]);
}
return 0;
}
void calculatePay(vector<Employee>& buisness)
{
if (buisness.HoursWorked <= 40)
{
buisness.straightTimePay = buisness.hourlyWage * buisness.HoursWorked;
buisness.overTimePay = 0;
}
else
{
buisness.straightTimePay = buisness.hourlyWage * 40;
buisness.overTimePay = buisness.hourlyWage * 1.5 * (buisness.HoursWorked - 40);
}
buisness.netPay = buisness.straightTimePay + buisness.overTimePay;
if (buisness.status == 'F')
buisness.netPay -= 10;
}
void displayEmployee(vector<Employee> buisness)
{
int precisionSetting = cout.precision();
long flagSettings = cout.flags();
cout.setf(ios::fixed | ios::showpoint);
cout.precision(2);
cout << setw(20) << buisness.name << setw(15) << buisness.ssn << setw(12) << buisness.hourlyWage;
cout << setw(14) << buisness.HoursWorked << setw(18) << buisness.straightTimePay;
cout << setw(14) << buisness.overTimePay << setw(6) << buisness.status << setw(10) << buisness.netPay << endl;
cout.precision(precisionSetting);
cout.flags(flagSettings);
}
At the very least.. You have the line:
calculatePay(buisness[index]);
So clearly we all calling a function calculatePay and we're passing it an Employee.
But your function prototype says that it takes a std::vector<Employee>. You probably intended for the functions to take Employee & instead.
You should call vector push_back with the element to put in:
Employee employee;
// assign values to employee
ss << employee.ssn;
ss << employee.name;
business.push_back(employee);
Although the compiler error logs seem tedious, but you can almost always get enough information from the error logs. Compiling under gcc 4.2.1, the error logs says :
error: invalid initialization of reference of type ‘std::vector<Employee, std::allocator<Employee> >&’ from expression of type ‘Employee’ on the line of calling method calculatePay(). We can infer that you passed Employee to and function which want an vector of Employee as parameter. You can fix this by change calculatePay(vector<Employee>& buisness) to calculatePay(Employee& buisness). And that will fix error: ‘class std::vector<Employee, std::allocator<Employee> >’ has no member named ‘HoursWorked’
I am getting an error saying the operand "<<" (right before times3(x) in the main function ) does not match the operand types being outputted in that line. What am I doing wrong? I searched for errors similar to it and found that its an inclusion error but i thought having would fix it. Also, countdown(seconds) in the main function is not being recognized and giving me an error. Why is that? The problems keep occurring when working with void.
'
#include <iostream>
#include <string>
#include <cstdlib>
#include <limits>
using namespace std;
bool die(const string & msg);
double triple(double x);
double times9(double x);
void triple(double & result, double x);
void times3(double & x);
void countdown(unsigned seconds);
bool restore();
int main(){
double x;
cout << "x: " << endl;
cin >> x;
cout << "The triple of " << x << " is " << triple(x) << endl;
cout << "9 times of " << x << " is " << times9(x) << endl;
cout << "3 times of " << x << " is " << times3(x) << endl;
unsigned seconds;
cout << "seconds: " << endl;
cin >> seconds;
cout << countdown(seconds) << endl;
}
bool die(const string & msg){
cout << "Fatal error: " << msg << endl;
exit(EXIT_FAILURE);
}
double triple(double x){
return 3 * x;
}
double times9(double x){
return 3 * triple(x);
}
void triple(double & result, double x){
x = 3 * x;
}
void times3(double & x){
x = triple(x);
}
void countdown(unsigned & seconds){
unsigned count = seconds;
cin >> seconds || die("input failure");
for (unsigned i = seconds; i <= size; i--){
cout << i << endl;
}
cout << "Blast off! " << endl;
}
bool resotre(){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
return cin.good();
}'
As mentioned in earlier answer, you need to change the return type of your function from void to the data type of variable your trying to print.
Another issue in your code is with function void countdown(unsigned & seconds)
Declaration and definition of the functions are different.
You have declared it as void countdown(unsigned seconds); but at the time of defining it you are using void countdown(unsigned & seconds). In declaration you are declaring it to take arguments by value but in definition you are making it to take arguments by reference.
Also in the for loop of the function countdown you have written
for (unsigned i = seconds; i <= 0; i--), this won't print any output, since your condition is i<=0, i think you tried to type i >= 0. :)
times3 returns void. Try:
times3(x);
cout << "3 times of " << x << " is " << x << endl;
Or have times3() return double instead of passing by reference.
double times3(double x);
I'm sure I'm doing something wrong, but I just can't figure it out. I've created an object with integer data members, and I want to have a member function return the quotient of it's members as a floating point value, which it does. It then appends some additional stuff. The output is below the program, which should run as is.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class Rational
{
public:
explicit Rational(int = 0, int = 1);
double getRationalAsDouble() const;
private:
int numerator;
int denominator;
};
Rational::Rational(int numerator, int denominator)
{
if (denominator == 0)
this->denominator = 1;
else
this->denominator = denominator;
this->numerator = numerator;
}
// ******* Problem Function *********
double Rational::getRationalAsDouble() const
{
double a = 0.0, b = 0.0;
a = static_cast<double>(numerator);
b = static_cast<double>(denominator);
cout << endl << "a = " << a;
cout << endl << "b = " << b;
cout << endl << "a/b = " << (a/b);
}
// ******** End Problem Function ********
int main()
{
{ //Create a new Scope so that I can view Destructor Message, not used here
Rational c(2, 6);
int data = 10;
cout << c.getRationalAsDouble(); // prints rational object c as double, but not really
cout << "\n\n";
} // End of Scope
return 0;
} // end main
And here's the output:
a = 2
b = 6
a/b = 0.3333332.31196e-317
I've been playing around, and if I change the function to have any regular division in it, it works fine. What's really interesting is if I add any output after the cout << endl << "a/b = " << (a/b); line, that output is handled before (a/b) part of the line. Any help would be greatly appreciated! Thank you in advance for your time.
Solution:
The function wasn't returning anything. When the code was changed to:
double Rational::getRationalAsDouble()
{
return static_cast<double>(numerator)/denominator;
}
It worked as expected. Thank you tc.
Three problems:
You want to print endl at the end of the line, not the "beginning". Your code ends up doing (effectively) cout << endl << "a/b = " << (a/b); ... cout << c.getRationalAsDouble(); cout << "\n\n"; which prints the two doubles 0.333333 and 2.31196e-317 next to each other with no space.
You want (perhaps) cout << "\n" << endl instead of cout << "\n\n". endl causes the stream to be flushed; plain "\n" might not.
Rational::getRationalAsDouble() is not returning a value. Listen to your compiler warnings.
The fix looks something like
double Rational::getRationalAsDouble() const
{
double a = 0.0, b = 0.0;
a = static_cast<double>(numerator);
b = static_cast<double>(denominator);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "a/b = " << (a/b) << endl;
return a/b;
}
Your implementation of Rational::getRationalAsDouble() can be simplified to:
double Rational::getRationalAsDouble() const
{
return 1.0*numerator/denominator;
}
I think you had everything else there for debugging purposes, and hence are not really needed.
I am having trouble with a program that uses void functions. I have never used them before so I'm a bit lost. My program has a 3 sets of cities. It is supposed to get the three cities in one of the sets and figure out how long the flight is. My problem is that I keep getting the error that my variables are undefined. This is the first program I have tried using void functions. I have tried initializing every variable by itself but I don't think that is the correct way to do it or is it? Any help would be appreciated. Here is my code:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void readFile (int wall1, double &lat1, double &lon1, string &city1,
double &lat2, double &lon2, string &city2,
double &lat3, double &lon3, string &city3);
void intro();
void askDataSet(int &w);
//--------------------------------------------------
int main()
{
intro();
askDataSet(int &w);
string name;
int lat1, lat2, lat3, , lon1, lon2, lon3, beginLat, beginLon, beginCity, midLat, midLon, midCity, endLat, endLon, endCity;
string city1, city2, city3;
readFile (beginLat, beginLon, beginCity, midLat, midLon, midCity, endLat, endLon, endCity);
cout << "The First City at coordinates " << beginLat << " and " << lon1 << " is: " << city1 << endl;
cout << "The Second City is at coordinates " << beginLat << " is " << lon2 << ": " << city2 << endl;
cout << "The Third City is at coordinates " << beginLat << " is " << lon3 << ": " << city3 << endl;
leg1 = dist( beginLat, beginLon, midLat, midLon);
leg2 = dist( midLat, midLon, endLat, endLon);
nonstop = dist( leg1-leg2 );
cout << "It is " << dist << "fewer miles for non-stop" << endl;
system("pause");
return 0;
}
void readFile (int &wall1, double &lat1, double &lon1, string &city1,
double &lat2, double &lon2, string &city2,
double &lat3, double &lon3, string &city3)
{
ifstream dataIn;
dataIn.open("cities.txt");
if(dataIn.fail())
{
cout << "Error. File does not exist. " << endl;
exit(1);
}
dataIn >> lat1;
dataIn >> lon1;
dataIn.get();
getline(dataIn, city1);
dataIn >> lat2;
dataIn >> lon2;
dataIn.get();
getline(dataIn, city2);
dataIn >> lat3;
dataIn >> lon3;
dataIn.get();
getline(dataIn, city3);
}
void intro()
{
cout << "In this lab we will try to figure out how much shorter it is to fly non-stop compared to one-stop." << endl;
cout << endl;
}
void askDataSet(int &w)
{
cout << "Which set of cities would you like to figure the distances for? " << endl;
cin >> w;
}
To give back a value from a void function via a reference-parameter, a variable has to exist in the caller's scope which is given as the parameter.
So in your case, for example to call askDataSet, you first have to declare an int to hold the result:
int w;
askDataSet(w);
Then askDataSet will write into your integer variable and you can use it after the call.
Further points I noticed with the code:
For the readFile call, the variables passed must have the same type as the parameters (double, not int).
There is an extra comma in the declarations before the readData call: "lat3, , lon1"
Maybe you'll want to replace beginLat, midLon etc. with lat1, lon2 (or the other way around).
readFile seems to have an unused first argument int wall1, which is missing in the readFile-call in main.
The dist function is not defined and at the end of main you try to print it.
To use system and exit, you should #include <cstdlib>.