I have just started with C++ and as a training excercise wrote this program. It takes some variables, uses them for calculations and then shows the results and saves them to a file.
Here's the problem: If i use this program without calculations.cpp and un-commenting shown lines in main(), everything works perfectly.
However, if i try moving calculations to a seperate file, then the program asks for input 2 times. I reallize it is because i call upon certian functions twice. What i dont get is how to, i dunno, store the variable and call for it from diffrent places. I tried & and *, but that didnt help me (must have misused or misundrestood them). Tried struct and class public:, but somehow that didnt work either; maybe too advanced for me for now.
Can someone point me to a tutorial on how to move variables to multiple functions without said functions running every time ?
#include "latticeHeader.h"
int main()
{
std::cout << welcomeMessage() << std::endl;
int h = millerIndex('h'); //hkl was i 3 diffrent functions, someone showed me how to do it once with 3 'name' parameters
int k = millerIndex('k');
int l = millerIndex('l');
// long double wl = defineWaveLength();
// long double t = doubleTheta();
longdouble d = lattSpacing();
longdouble a = lattConstant();
// long double d; //instead of the above
// long double a; //instead of the above
// d =(wl/(2*sin(t))); //equation from calculations.cpp
// a = sqrt(( pow( h, 2 ) + pow( k, 2 ) + pow( l, 2 ) ) *( pow( d, 2 ) ) ); //equation from calculations.cpp
std::cout << "(" << h << k << l << ")" << "\t" << a << "\t" << d << std::endl; //shows result
std::ofstream o( "Lattice Parameters.txt", std::ios::app ); //create txt file with name and append
o << "hkl(" << h << k << l << ")\t a=" << a <<"A\t d_hkl " << d << "A" << std::endl; //saves results to a file
std::cout << std::endl << std::endl;
std::cout<<"Calculate another ? (y/n)";
char rerun;
std::cin>>rerun;
if (rerun == 'y' || rerun == 'Y')
{
return main();
}
else
{
std::cout << "Press any key to exit" << std::endl;
}
}
You already calculated l,h,k,d in your main() function. Then in function main() you call lattConstant(h, k, l, d); which means you pass the values of h, k, l, d respectively in the function main() to the corresponding variables (parameters) h, k, l, d in lattConstant(). And when the function lattConstant() executes the function uses these values you have passed to calculate and return the result for you.
Yes. I made a mistake by forgetting that millerIndex() is called in main() and then lattConstant() is called also from main(), so main() has all the parameters.