[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1358
  • Last Modified:

Iterate elements name in c/c++ structure

Is there any known way to iterate through the element names of a structure at compile time to build a series of ?  

typedef struct
{
  char element1[50];
  char element2[50];
  char element3[50];
.
.
}

I'd like to be able to "print" the entire structure to either a char or file stream like so,

myStruct.element1 => 'Value1'
               element2 => 'Value2'
               element3 => 'Value3'

Functionality similar to the PHP 'print_r' function.

I know that the names are not available at run time.  I have built a macro that is close

#define __dump(a, x, y) fp_exception_log << "myStruct[" << x << "][" << y << "]." << #a << ": " << myStruct[x][y].a << std::endl

but I have to enter all the element names individually.  (__dump(element1, 0, 0)... )If I could iterate through the struct to get the names, that would be great as the struct I am dealling with is quite long and subject to changes frequently.

Don't know if this can be done or not, just though I'd float it out there and see if any one has cracked this nut before.

Thanks!
0
cvhoyt
Asked:
cvhoyt
  • 2
1 Solution
 
TommySzalapskiCommented:
I'm not sure what you mean. The structure of the struct itself changes? What I would do is make an element struct and have it contain the name and the element

struct Element
{
  char name[50];
  char value[50];
};

#define NUM_ELEMENTS 5

struct myStruct
{
  struct Element elements[NUM_ELEMENTS];
};

Then you just use a for loop
for(int i = 0; i < NUM_ELEMENTS; ++i)
  output myStruct.elements[i ].name //blah blah
0
 
TommySzalapskiCommented:
If you insist on doing it the old way, you could use Excel to speed up the process of typing all the lines.

Or just copy the insides of the struct to where the output lines need to be and use the find/replace feature of your IDE
Replace '  char ' with printf( or whatever and '[50];' with the rest.
Make sure to only do the replace in that selection of come.
0
 
ssnkumarCommented:
You cannot iterate thru the struct members as you do in case of an array.
You will have to access each of them by their name and do the operation.
0
 
cvhoytAuthor Commented:
Yes, I have come to the realization.  I'll have to do with my macro.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now