The task is to write a function that prints out the const string& that is being called in the main, and then it prompts for two inputs, which will be used later in another function. Plus the function is being used twice, with two different strings in the callout.
I have it so that it works, but the const string& is getting duplicated for some reason, and I cannot figure out why.
#include <iostream>
#include <iomanip>
#include <cmath>
usingnamespace std;
void read_function(const string& prompt, double& u, double& v);
int main()
{
double u1, v1; // coordinates of first vector
double u2, v2; // coordinates of second vector
read_function("Enter first vector (2 floats): ", u1, v1);
read_function("Enter second vector (2 floats): ", u2, v2);
return(0);
}
void read_function(const string& prompt, double& u, double& v){
double u1(0.0), v1(0.0), u2(0.0), v2(0.0);
cout << prompt;
cin >> u1 >> v1;
cout << prompt;
cin >> u2 >> v2;
}
So apparently I have something wrong in the syntax. I have read the tutorials, lecture notes, etc. I cannot figure it out, and I am tired of trial by error which is costing me hours of experimenting so far.
You are printing out the prompt twice in your function, and assigning the input values to temporary variables that go out of scope when the function ends. You are not assigning the input values to your passed parameters.
Since you want to pass by reference, perhaps, a way to write the function would be like...
1 2 3 4 5 6
void read_function(const string& prompt, double& u, double& v)
{
cout << prompt;
cin >> u >> v;
}
Also, since you are using the string library, you should include it #include <string>
While some compilers would allow to use the string without including it, others are not so forgiving.
I figured since there were two different strings I needed to cout twice. But essentially its being called twice in the main, and that is using the same function each time, But using the parameters within the call because of the pass by reference.
That was a simple fix, but you helped "un"complicate my thinking.
And so the "cin" prompt will put the values into the memory location for u1, v1, u2, v2 so that I can use those variable later in another function...( correct if I am wrong, please)?
And so the "cin" prompt will put the values into the memory location for u1, v1, u2, v2 so that I can use those variable later in another function
Variables u1/v1/u2/v2 are only usable in your function, they are not visible anywhere outside of your function.
The variables you declare in main() are not the same ones you declare in your function, even though you use the same name. To your compiler they are completely different.