Reputation: 17
I have a function which takes in two int values, does some processing and then returns the processed values in the form of a struct to the calling function.
The following is my called function:
auto start_end(){
bool cond = false;
int xd = 0;
int yd = 0;
std::cout<<("Please enter a desired x coordinate")<<std::endl;
std::cin>>xd;
while(std::cin.fail()){
std::cout<<("That is not a valid integer. Please enter a valid x co-ordinate")<<std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cin>>xd;
}
std::cout<<("Please enter a desired y coordinate")<<std::endl;
std::cin>>yd;
while(std::cin.fail()){
std::cout<<("That is not a valid integer. Please enter a valid y co-ordinate")<<std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cin>>yd;
}
struct xy{int x_received; int y_received;};
return xy{xd,yd};
}
We can see that the struct xy returns two values xd, yd in the above function start_end().
The following is my calling function:
int main(int argc, const char * argv[]) {
std::cout <<("A-Star-Algorithm for Project 2 obstacle map")<<std::endl;
int x_start = 0;
int y_start = 0;
int init_point = start_end();
return 0;
}
So when I try to store the return values xd, yd in the variable init_point, I get the error:
No viable conversion from 'xy' to 'int'
Since, I got this error I tried to write the receiving variable as a 2 - index array:
int init_point[2] = start_end();
When I try to do in this way, I get the following error:
Array initializer must be an initializer list
My exact question : What is the appropriate manner in which I have to receive the values xd and yd returned by function start_end() when it is called inside function int main() ?
Upvotes: 0
Views: 68
Reputation: 14987
std::tuple
is to your relief (live)
#include <iostream>
#include <tuple>
auto start_end() {
auto x = 1, y = 2;
return std::make_tuple(x, y);
}
int main() {
int x, y;
std::tie(x, y) = start_end();
std::cout << x << ' ' << y << std::endl;
}
Upvotes: 2
Reputation: 7111
You need to move your struct
into a place that can be seen by start_end
and main
:
struct xy { int x; int y; };
xy start_end()
{
...
return { xd, yd };
}
int main()
{
}
Then you can either assign it with auto
or use the type name xy
:
int main()
{
auto xy1 = start_end();
xy xy2 = start_end();
}
Or you can use std::pair
or std::tuple
.
Upvotes: 4