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>.
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 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);
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've tried many times to fix this error but I'm not sure what to do. For both the addBooks and displayBooks functions I am getting a "function does not take 1 arguments" error, though the vector should just be one argument.
struct bookStruct
{
char title[40];
char author[40];
int pages;
int year;
};
enum menu { display=1, add, end} ;
void displayOptions();
void displayBooks();
void addBooks();
int main(){
vector<bookStruct> book(1);
string option = "display";
displayOptions();
cin >> option;
//std::strcpy(book[0].title, "a");
//std::strcpy(book[0].author, "a");
//book[0].pages = 0;
//book[0].year = 0;
while (option != "end"){
addBooks(book);
displayBooks(book);
}
return 0;
}
void displayOptions(){
cout << "1. Display list of books" << endl;
cout << "2. Add books" << endl;
cout << "3. Exit" << endl;
}
void displayBooks(vector<bookStruct> book){
for (int n = 0; n<book.size(); n++){
cout << book[n].title << " ; " << book[n].author << " ; "
<< book[n].pages << " ; " << book[n].year <<endl;
}
cout << endl;
}
void addBooks(vector<bookStruct> book){
int n = book.size()+1;
book.resize(book.size()+1);
cout << "Enter the book title: " << endl;
cin >> book[n].title;
cout << "Enter the author name: " << endl;
cin >> book[n].author;
cout << "Enter the number of pages: " << endl;
cin >> book[n].pages;
cout << "Enter the publication year: " << endl;
cin >> book[n].year;
}
Both addBooks and displayBooks take no arguments:
void displayBooks();
void addBooks();
yet you are calling them with arguments:
addBooks(book);
displayBooks(book);
The compiler is telling you this in its own words.
It looks like you need
void displayBooks(vector<bookStruct> book);
void addBooks(vector<bookStruct> book);
although it is more likely that you don't need to copy the vectors into the functions:
void displayBooks(const vector<bookStruct>& book);
void addBooks(const vector<bookStruct>& book);
Note you have definitions of one-parameter functions after main(). The main() function only considers the declarations that come before it.
void displayBooks();
void addBooks();
take no parameter, however you passed book into them, the compile cannot find both functions. therefore, error.
void displayBooks();
should be
void displayBooks(vector<bookStruct> book);
but as a better approach you can use:
void displayBooks(const vector<bookStruct> &book);
So that book vector is not copied while being passed into the method DisplayBooks
Your function is declared as
void addBooks();
but you are calling it with
addBooks(book);
Compiler obviously thinks it strange that you have no argument in the declaration, and then try to call it with an argument.
It is hard for me to advice exactly what you should do, since it's not clear from the code you have posted what the "right" thing is.