Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print every member of a structure

Tags:

c++

struct

Suppose I have a structure with 50 integers. Is there a way to print out the value of every integer without having to manually type it out?

Example:

struct foo
{
  int one; //= 1
  int two; //= 2
  int three; //= 3
  ...
  int fifty; //= 50
};
int main()
{
    foo bar;
    int dream;
    cout << someThing(bar) //prints 12345...50
}

edit: I realize data like this should be stored in an array, this is just a hypothetical question. I am just curious if something like this exists.

like image 336
user3331346 Avatar asked Feb 26 '14 05:02

user3331346


1 Answers

Well, you probably should have used arrays for such a thing in the first place since that would have made this task so much easier :-)

However, you could try casting the structure into an array and printing that out. There's no guarantee it will work in every implementation since it may be that the structure gets padded differently to an array, though I couldn't imagine why, but you may get lucky:

int *base = (int*)(&bar.one);
for (int i = 0; i < 50; i++)
    std::cout << "Item #" << (i + 1) << " = " << base[i] << '\n';

By way of example, the following program:

#include <iostream>

struct foo {
  int one, two, three, four;
};

int main() {
    foo bar;
    bar.one = 42;
    bar.two = 314159;
    bar.three = 271828;
    bar.four = 1414;

    int *base = (int*)(&bar.one);
    for (int i = 0; i < 4; i++)
        std::cout << "Item #" << (i + 1) << " = " << base[i] << '\n';
    return 0;
}

outputs this:

Item #1 = 42
Item #2 = 314159
Item #3 = 271828
Item #4 = 1414

in my environment (Debian 7, g++ 4.7.2):

But, if you want to treat them like an array, they really should be an array.

like image 96
paxdiablo Avatar answered Nov 14 '22 23:11

paxdiablo