Lee Shyu
Lee Shyu

Reputation: 13

C++ How to pass two structs from function?

Here's the main function ex1-1.cpp

#include <iostream>
#include "ex1-1.h"
using namespace Complex;

int main(int argc, char *argv[])
{

Cplex a={0.0,0.0}, b={0.0,0.0},c={0.0,0.0}, d={0.0,0.0}; 
// use struct named Cplex under namespace Complex
ReadTextFile(argv[1], a, b);// process text file


std::cout<<a.real<<std::showpos<<a.image<<std::endl;
std::cout<<b.real<<std::showpos<<b.image<<std::endl;

return 0;
} 

one header ex1-1.h

#include <iostream>
#include <fstream>
namespace Complex 
{
    typedef struct
{
    double real;
    double image;
}Cplex;


Cplex ReadTextFile(char argv[],Cplex a,Cplex b);

}

and one for functions ex1-1-function.cpp

#include<iostream>
#include<fstream>
#include<iomanip>
#include "ex1-1.h"
namespace Complex
{

Cplex ReadTextFile(char argv[],Cplex a,Cplex b)
{

    std::ifstream fin;
    fin.open("complex.txt");

    char i;
    fin>>a.real>>a.image>>i;
    fin>>b.real>>b.image>>i;
    std::cout<<std::noshowpos<<a.real<<std::showpos<<a.image<<"i"<<std::endl;
    std::cout<<std::noshowpos<<b.real<<std::showpos<<b.image<<"i"<<std::endl;

    return (a,b);
};

}

the text file complex.txt looks like this

1.5+6i
-2-10i 

I tried to define a type of structure called Cplex, including two members, real and image

declare Cplex a and Cplex b

then use function ReadTextFileread(argv[1],a,b) to read in two complex numbers and store in the structures a and b

then return a and b at once

But no matter how I tried the main function can only read b instead of both

How can I pass two structures to the main function at once?

Or should I use Array to contain two structures then pass it?

Upvotes: 1

Views: 484

Answers (2)

r3mus n0x
r3mus n0x

Reputation: 6144

You can use std::pair to couple two values together:

std::pair<Cplex> ReadTextFile(char argv[])
{
    Cplex a, b;
    ...
    return { a, b };
};

Then use them like this:

#include <tuple>
...
Cplex a, b;
std::tie(a, b) = ReadTextFile(argv);

Note that std::tie is only available since C++11.

Or if you can use C++17 it will be even simpler to use structured binding:

auto [a, b] = ReadTextFile(argv);

Upvotes: 4

rks
rks

Reputation: 622

In C & C++ you can return only one value from the function.

Instead use pass by reference to pass the structs 'a' and 'b' and then fill the values within the function.

Declaration:

void ReadTextFile(char argv[],Cplex &a,Cplex &b);

Definition:

void ReadTextFile(char argv[],Cplex& a,Cplex& b)
{

    std::ifstream fin;
    fin.open("complex.txt");

    char i;
    fin>>a.real>>a.image>>i;  // values filled here can now be read in the caller i.e main.
    fin>>b.real>>b.image>>i;
    std::cout<<std::noshowpos<<a.real<<std::showpos<<a.image<<"i"<<std::endl;
    std::cout<<std::noshowpos<<b.real<<std::showpos<<b.image<<"i"<<std::endl;

    return;
};

Hope this helps.

Upvotes: 1

Related Questions