Difficulty with Calling Functions from Separate Source Files in Visual C++ **UPDATE** - c++

I really hope this falls within guidelines, but I have a potential silly question: I'm trying to get a good feel of how multiple header and source files fit together in a C++ program. To do so, I'm making a calculator for simple physical formulae.
#include "stdafx.h"
#include "rotationalKinematics.h"
#include "Kinematics.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
//declare local variables:
int fieldChoice = 0;
//query field of equations:
cout << "What physical properties would you like to solve for?\n (1) kinematics\n (2) rotational kinematics\n Please enter number: ";
cin >> fieldChoice;
if (fieldChoice == 1) {
int mainKinematics();
return 0;
}
if (fieldChoice == 2) {
int mainRotationalKinematics();
return 0;
}
return 0;
}
The program compiles without error, and the two functions mainKinematics() and mainRotationalKinematics() are defined and declared in separate .cpp and .h files, respectively. For example, I've included the a header and a source file for mainKinematics() below:
#include "stdafx.h"
#include "Kinematics.h"
#include <iostream>
#include <cmath>
using namespace std;
//function declaration:
double kinDeltaX_acceleration(double velocityInitial, double deltaTime, double acceleration);
int mainKinematics()
{
//local variable declaration:
double velocityInitial = 0;
double velocityFinal = 0;
double velocityFinalSquared = 0;
double acceleration = 0;
double deltaX = 0;
double deltaTime = 0;
int solveFor = 0;
//query variable to solve for:
cout << "What variable would you like to solve for?\n (1) DeltaX w.r.t. acceleration\n (2) DeltaX w.r.t. velocity\n (3) Final velocity\n (4) Final velocity squared\n Please enter number: ";
cin >> solveFor;
//query for values based on solveFor choice:
if (solveFor == 1) {
cout << "Please enter value for velocityInitial: ";
cin >> velocityInitial;
cout << "Please enter value for deltaTime: ";
cin >> deltaTime;
cout << "Please enter value for acceleration: ";
cin >> acceleration;
//function call:
deltaX = kinDeltaX_acceleration(velocityInitial, deltaTime, acceleration);
cout << deltaX;
}
if (solveFor != 1 && solveFor != 2 && solveFor != 3 && solveFor != 4)
{
return 0;
}
return 0;
}
//functions:
double kinDeltaX_acceleration(double velocityInitial, double deltaTime, double acceleration)
{
//local variable declaration:
double result;
result = velocityInitial*deltaTime + .5 * acceleration * pow(deltaTime, 2);
cin.clear();
cin.sync();
cin.get();
return result;
}
and the related Kinematics.h header file:
#ifndef Kinematics
#define Kinematics
#pragma once
//function declarations:
double kinDeltaX_acceleration(double velocityInitial, double deltaTime, double acceleration);
double kinDeltaX_velocity(double velocityInitial, double velocityFinal, double deltaTime);
double kinVelocityFinal(double velocityInitial, double acceleration, double deltaTime);
double kinVelocityFinalSquared(double velocityInitial, double acceleration, double deltaX);
int mainKinematics();
#endif
When I solely compiled the Kinematics.cpp file (above) it worked fine. However, when I tried to tie the Kinematics.cpp file and the rotKinematics.cpp files together into one overarching main file (shown in the first code example) I run into the following problem: the code compiles without error, it takes user input for which function to access, and then immediately closes without seeming to execute the called function from a separate source file. Am I doing something wrong in the way I'm calling the functions?
Any help is appreciated immensely and thank you for your time!!
P.S. I realize that I declare the functions in both the .cpp and .h files; when I do not include the declaration in the .cpp file the compiler returns errors. This suggests that I'm doing something wrong, though I haven't been able to figure out what.
UPDATE
Hello! Thank you all so much for weighing in on this! With the resources provided I've found a workaround as such:
if (fieldChoice == 1) {
int val = -1;
val = mainKinematics();
return 0;
Referencing the function in my original script wasn't actually returning anything; by creating an intermediate object (val) to hold the final value the script now seems to work as intended. What do you folks think? Is this an okay solution?

Related

C++ bug uninitialized variable

I am instructed to write a program where the user inputs two values, can be with decimals. Then create a void function that changes the precision to 4 digits. I created a program and it runs the first value (x) just fine but for some reason, it's giving me an error saying the second variable is uninitialized (h) any advice would be appreciated! I think that I've been looking at it for too long and just can't spot it!
Below is the code:
#include <iostream>
#include<cmath>
using namespace std;
void display_it(double x, double h);
int main(void) // getting input from user and displaying output
{
double x, h;
cout << "Please enter 2 values to be displayed with precision.\n";
cin >> x, h;
cout << x << endl;
cout << h << endl;
return 0;
}
void display_it(double x,double h) //does the precision change of x and h
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(4);
}
This line:
cin >> x, h;
is not reading in 2 values from cin. It's actually only reading in 1 value, after which the expression h that's after the , is evaluated (which does nothing). So the warning/error about h being uninitialized is correct.
The correct way to read 2 values is:
cin >> x >> h;

Hello, the program on Functions (pass by reference/pass by value) and I'm not entirely sure what is wrong with my program

Can someone give advice or guidance on what is wrong with my program? I do have the program fully written out, I am not sure where to add the function definition and function prototype to my program. This program involves pass by value and pass by reference. Also, any helpful notices on small errors will be appreciated
#include "pch.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
//Declare Variables
double amount = 22.66;
int num;
int dollars;
int quarters;
int dimes;
int nickels;
int pennies;
double x = 22.25;
double y = 55.55;
//Input
cout << "Please enter your dollar amount: ";
cin >> amount;
void showMenu() //function prototype
{
cout << "A. Money Exchange function" << endl;
cout << "B. Find Max Solution" << endl;
cout << "E. Exit" << endl;
cout <<"Please enter your choice:"<<endl;
}
void MoneyExchange(float amount, int& dollars, int& quarters, int& dimes,
int & nickels, int & pennies) // function prototype
{
int amount = 0, Remainder;
amount = amount * 100;
dollars = amount / 100;
Remainder = amount - (dollars * 100);
quarters = Remainder / 25;
Remainder = Remainder - (quarters * 25);
dimes = Remainder / 10;
Remainder = Remainder - (dimes * 10);
nickels = Remainder / 5;
Remainder = Remainder - (nickels * 5);
pennies = Remainder / 1;
}
double max(double x, double y) //function prototype
{
double max;
if (x >= y)
max = x;
else
max = y;
system("Pause");
return 0;
}
To use a function, you need to have a function method declaration (tell compiler/linker that this function exists) and implementation (stuff that function method does).
Here is a barebones example
void doStuff(); //im function declaration/prototype
void doMoreStuff(); //im function declaration/prototype
int main()
{
void doMoreStuff() //dont nest me in here!
{
cout << "doMoreStufff runs" << endl;
}
doStuff();
doMoreStuff();
return 1;
}
void doStuff() //im function implementation
{
cout << "doStuff runs" << endl;
}
Key take aways:
1) What you call a function prototype in your code is function implementation
2) No nesting implementation. for example: Dont do this
int main()
{
void doMoreStuff() //dont nest me in here!
{
cout << "doMoreStufff runs" << endl;
}
doStuff();
doMoreStuff();
return 1;
}
void doStuff() //im function implementation
{
cout << "doStuff runs" << endl;
}
(side note: one could nest anonymous/lambda functions inside)
3) In your case it doesnt matter if you stick method implementation above or below main{} implementation, just make sure you have your functions declared above main{} implementation (where these methods are used)
TLDR Poor naming conventions, not prototyping/declaring and defining properly, mismatched variable types, hiding value of amount (22.66, then cin, then int amount = 0 in MoneyExchange), unused code (max function), menu is not functional.
You are trying to define functions inside the main function like such:
int main() {
// ...
void showMenu() {
// code to do stuff
}
// ...
return 0;
}
It does not work like this. If you want to define and declare showMenu, so it can be used in main, try this. (See above)
void showMenu() {
// code to do stuff
}
int main() {
// ...
showMenu();
// ...
}
If you do not prototype the function, you must declare it above the main function. Otherwise it won't compile. (See above)
Try this (See below) if you want to prototype. You can have your prototypes in the main file or in a header file which you can include in main.
void showMenu(); // prototype
int main() {
// ...
showMenu();
// ...
}
void showMenu() {
// code to show the menu
}
If you want to define a function inside another, you should use a lambda expression.
Problems with your program:
-You define amount as a double of value 22.66 and then write over it when you cin >> amount. You only need to set the value once, so remove the cin or (preferably) change it to
double amount;
-Your functions and procedures, showMenu, MoneyExchange and max need to be moved outside of main, and prototyped or defined before main.
-You should find a naming convention which works for you and stick to it. You have procedure names starting with a capital MoneyExchange and then one starting with lower case, showMenu. Stick to the same, I'd use moneyExchange and showMenu.
You have done the same thing with variables, have a look here https://code.tutsplus.com/articles/9-confusing-naming-conventions-for-beginners--net-15584 this explains some naming conventions.
-Max function does not return anything. It must return a double, as you've declared. E.G.
double max(double x, double y) {
// ...
return 0.0;
}
-In MoneyExchange you declare a new int called amount, which you have declared locally in main as a double. You also set the value to 0, not the amount you inputted using cin.
-When you declare MoneyExchange, amount is taken as a float. So you pass a double, receive it as a float and then make a new int called amount... Stick to one data type. You also don't pass it by reference.
-You don't use the max function anywhere in this code.
-You don't get input from the menu, so the user does not have an option. I would use a switch statement. See this link http://www.cplusplus.com/forum/general/156582/ .

Having issues with void function

I'm trying to the program to display the bonus, but the programs renders an answer to 0. I am extremely new to c++ so any guidance would be greatly appreciated.
Here's the code:
#include <iostream>
#include <iomanip>
using namespace std;
//function prototypes
void enterItems(double, double);
void calcAndDisplayBonus(double &salesAmt, double &rate);
int main()
{
//declare variables
double sales = 0.0;
double bonusRate = 0.0;
//enter input values
enterItems(sales, bonusRate);
//calculate and display bonus
cout << fixed << setprecision(2);
calcAndDisplayBonus(sales, bonusRate);
system("pause");
return 0;
} //end of main function
//*****function definitions*****
void enterItems(double salesAmt, double rate)
{
cout << "Enter sales: ";
cin >> salesAmt;
cout << "Enter bonus rate (in decimal form): ";
cin >> rate;
} //end of enterItems function
void calcAndDisplayBonus(double &salesAmt, double &rate)
{
cout << "Bonus: $" << salesAmt * rate << endl;
} //end of calcAndDisplayBonus function
When you call enterItems, you are passing parameters by copy. This means that your changes won't affect the variables available in the scope of the caller.
To solve it, you can either pass a couple of references or pointers, as well as rely on a pair returned from the function as a result, and so on.
As an example, by writing:
void enterItems(double &salesAmt, double &rate)
You'll actually solve the problem above mentioned.
Another valid prototype is:
void enterItems(double *salesAmt, double *rate)
Even though this one asks for a small set of changes all around your code (the example, of course).
There is a plenty of possible solutions, hoping these ones will give you an idea of what's wrong.
Your function
void enterItems(double salesAmt, double rate)
is taking two double-parameters by value, this means, your changes you do inside the function will not be visible from the outside. You could take the doubles by reference:
void enterItems(double &salesAmt, double &rate)
but i'd prefer to return the values, but since you can only return a single value you'd need two functions:
double enterSales()
{
double tmp;
cout << "Enter sales: ";
cin >> tmp;
return tmp;
}
double enterBonus()
{
double tmp;
cout << "Enter bonus rate (in decimal form): ";
cin >> tmp;
return tmp;
}
//in your main:
double sales = enterSales();
double bonusRate = enterBonus();

Including multiple files with C++

This week my class took a spin and is teaching material not found in the book. I'm using Visual Studio 2010, the project is to take 5 numbers from the keyboard and get the average, but I have to use functions with a .h header file and corresponding .cpp file to receive credit. This is what I have so far
Main.cpp
#include <iostream>
#include "average.h"
using namespace std;
const int numbersinput=5;
int main ()
{
int numbers,sum,avg;
cout << "Hello, please enter 5 numbers you would like to see the average for." << endl;
for (int i = 0; i != numbersinput; ++i)
{
cin >> numbers;
sum += numbers;
}
int average(int sum);
cout << avg;
system ("PAUSE");
return 0;
}
The .h headerfile named average.h
#include <iostream>
using namespace std;
int average(int);
and the other .cpp file named average.cpp
#include <iostream>
#include "average.h"
using namespace std;
const int numbersinput=5;
int avg;
int average(int sum)
{
avg = sum /numbersinput;
return avg;
}
I can get a successful build, but I get this error after I enter the first number and press enter.
Run-Time Check Failure #3 - The variable 'sum' is being used without
being initialized.
What am I not getting here?
You might want to initialize sum to 0 before you start adding to it with +=:
So instead of int numbers,sum,avg;
You will have int sum = 0; etc.
Change this line:
int numbers,sum,avg;
To:
int numbers=0;
int sum=0;
int avg=0;
This gives the variables values- before they are initialized (given a value) they are undefined, which means that they could equal any value. By initializing them, you are giving them a number to add to when you make the sum.
Edit these lines:
int average(int sum);
cout << avg;
To:
cout << average(sum);
The function declaration for int average(int sum) is not called in the same way as it is declared. The ints are unnecessary. In my edited code, you can see that the returned value (average)is printed out, instead of being left without being used.
Also, as a general tip, try not to give variables the same name. Try to make the function variable sum be called sumToAverage or instead make the sum in main be called total. It is a good idea to pick variable names that are different, so you won't get confused.
You're saying :
sum += numbers
But you haven't initialized sum, so it will have some random value that's on the stack. Change your declaration of sum to:
int sum = 0;
Also, you're using global variables to pass information to functions, which isn't a good idea. Get rid of the avg variable and change average to:
int average(int sum, int numberofvalues)
{
int avg = sum / numberofvalues;
return avg;
}
You're also re-declared average in the body of main, which you don't need to do as it's in the header. Then, you can get the average in main by saying:
int avg = average(sum, numbersinput);
Now, main will look like this:
int main ()
{
int sum=0;
cout << "Hello, please enter 5 numbers you would like to see the average for." << endl;
for (int i = 0; i != numbersinput; ++i)
{
int number;
cin >> number;
sum += number;
}
int avg = average(sum, numbersinput);
cout << avg;
system ("PAUSE");
return 0;
}
Oh, and don't put using namespace std in header files!

Separate classes into separate files in C++

EDIT: Added the "addition" class in, accidentally forgot about it.
How do I separate classes into different files? I understand how classes work and how to make objects and things like that. However, I'm finding some confusion in the process of putting classes in different files. Thanks much for any help! Also, I am using CodeBlocks as an IDE. Here is my understanding so far:
Create new class, and CB gives you a ".h" and a new ".cpp".
The "Classname::Classname" at the beginning of the source file is a Scope Resolution Operator.
You use "#include classname.h" in your main source file to import its contents.
You can call functions from "main" by using the objects that you have declared.
This is my understanding so far, but I'm just confused on how to implement it. I have created a simple calculator with all the classes in one source file. It works fine, and I guess I'm pretty proud of it :) I know there is a lot easier way to make something like this, but I used classes and objects instead for the sole purpose of practice. Here's my code for the calculator. Also, I really apologize for the long post :/ Thanks, if you have come this far in reading it, and thanks especially if you can help me out a bit!
Here's my code in one source file:
#include <iostream>
using namespace std;
class Addition {
public:
float add (float x, float y) {
float sum;
sum=x+y;
return sum;
}
};
class Subtraction {
public:
float subtract (float x, float y) {
float dif;
dif=x-y;
return dif;
}
};
class Multiplication {
public:
float multiply (float x, float y) {
float prod;
prod=x*y;
return prod;
}
};
class Division {
public:
float divide (float x, float y) {
float quot;
quot=x/y;
return quot;
}
};
int op;
char cont;
int main()
{
do {
cout<<"Welcome to C++ Calculator v2!"<<endl;
cout<<"Select the number for which operation you want to use: "<<endl;
cout<<"1-Addition"<<endl;
cout<<"2-Subtraction"<<endl;
cout<<"3-Mutliplication"<<endl;
cout<<"4-Division"<<endl;
cin>>op;
if (op==1) {
float num1;
float num2;
Addition addobj;
cout<<"You have chosen Addition!"<<endl;
cout<<"Enter the first number you want to add: "<<endl;
cin>>num1;
cout<<"Enter the second number you wat to add: "<<endl;
cin>>num2;
float ans=addobj.add(num1, num2);
cout<<"The sum is "<<ans<<endl;
cout<<"Do you wish to continue? Y/N"<<endl;
cin>>cont;
}
if (op==2) {
float num1;
float num2;
Subtraction subobj;
cout<<"You have chosen Subtraction!"<<endl;
cout<<"Enter the first number you want to subtract: "<<endl;
cin>>num1;
cout<<"Enter the second number you want to subtract: "<<endl;
cin>>num2;
float ans=subobj.subtract(num1, num2);
cout<<"The difference is "<<ans<<endl;
cout<<"Do you wish to continue? Y/N"<<endl;
cin>>cont;
}
if (op==3) {
float num1;
float num2;
Multiplication multobj;
cout<<"You have chosen Multiplication!"<<endl;
cout<<"Enter the first number you want to multiply: "<<endl;
cin>>num1;
cout<<"Enter the second number you want to multiply: "<<endl;
cin>>num2;
float ans=multobj.multiply(num1, num2);
cout<<"The product is "<<ans<<endl;
cout<<"Do you wish to continue? Y/N"<<endl;
cin>>cont;
}
if (op==4) {
float num1;
float num2;
Division divobj;
cout<<"You have chosen Division!"<<endl;
cout<<"Enter the first number you want to divide: "<<endl;
cin>>num1;
cout<<"Enter the second number you want to divide: "<<endl;
cin>>num2;
float ans=divobj.divide(num1, num2);
cout<<"The quotient is "<<ans<<endl;
cout<<"Do you wish to continue? Y/N"<<endl;
cin>>cont;
}
} while (cont=='Y'||cont=='y');
if (cont=='N'||'n') {
cout<<"Thanks for using my program, goodbye!"<<endl;
}
return 0;
}
Ok, I will show you by doing your example:
subtraction.h
class Subtraction
{
public:
float subtract (float x, float y);
};
subtraction.cxx
#include "subtraction.h"
float Subtraction::subtract (float x, float y)
{
float dif;
dif=x-y;
return dif;
}
multiplication.h
class Multiplication
{
public:
float multiply (float x, float y);
};
multiplication.cxx
#include "multiplication.h"
float Multiplication::multiply (float x, float y)
{
float prod;
prod=x*y;
return prod;
}
and so on...
main.cxx
#include "subtraction.h"
#include "multiplication.h"
int main()
{
//use the classes just as before.
}
Also, I didn't put it in the code here, for simplicity, but go ahead and get into the habit of ensuring that your declarations are only included once. On a large project, this can get very nasty if you don't put these safeguards in.
#ifndef SUBTRACTION_H
#define SUBTRACTION_H
class Subtraction
{
....
};
#endif /*SUBTRACTION_H*/
here's something like Jonathan's example (I did not add the include guards for brevity, definitely do so though!), but with some duplication removed and some OO added for your learning pleasure. Note that while this is certainly not how an actual calculator would be implemented, it will hopefully give you some more understanding of C++ if you study it well enough.
mathoperation.h:
//a base class!
class MathOperation
{
public:
virtual float doit( float x, float y ) const = 0;
};
subrtaction.h:
class Subtraction : public MathOperation
{
public:
float doit( float x, float y ) const;
};
addition.h:
class Addition : public MathOperation
{
public:
float doit( float x, float y ) const;
};
subtraction.cpp:
#include "subtraction.h"
float Subtraction::doit( float x, float y ) const { return x - y; }
addition.cpp:
#include "addition.h"
float Subtraction::doit( float x, float y ) const { return x + y; }
main.cpp:
#include <iostream>
#include <string>
//yes this saves typing, but there reasons not to use it.. search SO!
using namespace std;
//this one avoids you having to copy/paste the similar parts
void DoIt( const MathOperation& op, const std::string& opName, const std::string& verb, const std::string& resultName )
{
cout << "You have chosen " << opName << "!" << endl;
cout<<"Enter the first number you want to " << verb << ": "<< endl;
//here you should actually check if the user really types in a number, and not "blablabla"
//and off course, put it in a seperate function so you can reuse it for num2
float num1;
cin>>num1;
float num2;
cout<<"Enter the second number you wat to " << verb << ": "<< endl;
cin>>num2;
cout<<"The " << resultName << " is " << op.doit( num1, num2 ) <<endl;
}
int main()
{
int op;
char cont = 'n';
do {
cout<<"Welcome to C++ Calculator v2!"<<endl;
cout<<"Select the number for which operation you want to use: "<<endl;
cout<<"1-Addition"<<endl;
cout<<"2-Subtraction"<<endl;
cout<<"3-Mutliplication"<<endl;
cout<<"4-Division"<<endl;
cin>>op;
//see how much shorter this is?
if( op == 1 )
DoIt( Addition(), "Addition", "add", "sum" );
else if (op==2)
DoIt( Subtraction(), "Subtraction", "subtract", "difference" );
else
cout << "Sorry I don't know this number" << endl;
cout<<"Do you wish to continue? Y/N"<<endl;
cin>>cont;
} while (cont=='Y'||cont=='y');
cout<<"Thanks for using my program, goodbye!"<<endl;
return 0;
}
It's good to name your files the same way as the class. It's not such a good idea in your case, beacause your classes are short, but each class should have its own 2 files - for example Subtraction.h and Subtraction.cpp. In the .h file you should put only the decaration - in your case:
class Subtraction
{
public:
float subtract (float , float);
}
In the .cpp file you should include the .h file and put the implementation. In your case:
float Substraction::subtract (float x, float y)
{
float dif;
dif=x-y;
return dif;
}
See also C++ Header Files, Code Separation and Why have header files and .cpp files in C++?
Hope this helps a bit! :)
It's good to have only one public class per file.
By convention filename is the same as the classname (with an extension like .h .hh or .hpp if some definitions are done in the file).
if you want to put different classes in different files, a simple text editor will help you to do that.