Printing Values of All Fields in a C++ Structure

auto generate code to print each field of struct in c++

I think you can just create a method in the struct A that prints all the members. Call it wherever you need to print all the data using A.PrintInternalData().

#include<iostream>

struct A
{
int a;
int b;
char * c;
float d

void PrintInternalData()
{
std::cout<<A.a<<std::endl;
std::cout<<A.b<<std::endl;
std::cout<<A.c<<std::endl;
std::cout<<A.d<<std::endl;
}
};

Printing the structure using a single line in C?

Glibc allows you to establish your own format specifiers for printf and family to let you print UDTs, which would not otherwise be possible, through some extensions.

#include <stdio.h>
#include <printf.h> /* For PA_POINTER */

struct MyStruct
{
int a;
double b;
};

struct print_info;
int handler(FILE *stream, const struct print_info *i,
const void* const *args)
{
const struct MyStruct *ptr = *( (const struct MyStruct**) (*args) );
int rc = fprintf(stream, "a: %d, b: %f\n", ptr->a, ptr->b);

return rc;
}

int print_arginfo (const struct printf_info *info, size_t n,
int *argtypes)
{
if (n > 0)
argtypes[0] = PA_POINTER;
return 1;
}

int main(void)
{
struct MyStruct s = {55, -3.14};
/* We're gonna use the M specifier */
int spec = 'M';
int rc = register_printf_function(spec, handler, print_arginfo);

if (rc != 0)
return 1;

printf("%M", &s);

};

You may find the documentation here.

C#: Printing all properties of an object

The ObjectDumper class has been known to do that. I've never confirmed, but I've always suspected that the immediate window uses that.

EDIT: I just realized, that the code for ObjectDumper is actually on your machine. Go to:

C:/Program Files/Microsoft Visual Studio 9.0/Samples/1033/CSharpSamples.zip

This will unzip to a folder called LinqSamples. In there, there's a project called ObjectDumper. Use that.

How to print struct variables in console?

To print the name of the fields in a struct:

fmt.Printf("%+v\n", yourProject)

From the fmt package:

when printing structs, the plus flag (%+v) adds field names

That supposes you have an instance of Project (in 'yourProject')

The article JSON and Go will give more details on how to retrieve the values from a JSON struct.


This Go by example page provides another technique:

type Response2 struct {
Page int `json:"page"`
Fruits []string `json:"fruits"`
}

res2D := &Response2{
Page: 1,
Fruits: []string{"apple", "peach", "pear"}}
res2B, _ := json.Marshal(res2D)
fmt.Println(string(res2B))

That would print:

{"page":1,"fruits":["apple","peach","pear"]}

If you don't have any instance, then you need to use reflection to display the name of the field of a given struct, as in this example.

type T struct {
A int
B string
}

t := T{23, "skidoo"}
s := reflect.ValueOf(&t).Elem()
typeOfT := s.Type()

for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
fmt.Printf("%d: %s %s = %v\n", i,
typeOfT.Field(i).Name, f.Type(), f.Interface())
}

How to get total number of elements in the structure

Not portably, generally, or safely, no.

Since the compiler might add padding for alignment and other reasons, which will make the size grow, it's not possible to rely on the value being correct.

If the number of elements matters, it's best to use an array.

By the way, this code:

int result = sizeof(b)/sizeof(*b);

is wrong and won't compile; b is not a pointer so *b is not a legal expression. You meant:

const int result = sizeof b / sizeof b.b0;

Also, as a side note, avoid using C++ keywords in C code, it can be somewhat confusing.

UPDATE I don't understand your reference to "bit fields". They look like this, and can only occur in structs:

struct strawberry {
unsigned short fields : 10;
unsigned short forever : 6;
};

Again, it's not possible to count them, since they don't even have byte sizes. But on the other hand, you wrote the definitions including the bit-widths for each field, so you should know how many there are, right?

how to save a structure in a vector and print out those values in C language?

c++ approach:

to store struct in a vector you declare first the vector

 vector<struct name_of_your_struct> name_of_vector; //the vector is still empty

then you declare a variable of struct like that

 struct name_of_your_struct     name_of_variable_type_struct;

you fill your struct with the adequate informations (first example move-$100)

name_of_variable_type_struct.name="move";
name_of_variable_type_struct.price=100;

then you push it inside your vector

name_of_vector.push_back(name_of_variable_type_struct);

you can repeat that many times with a loop

while(1)
{
cin >> name_of_variable_type_struct.name;
cin >> name_of_variable_type_struct.price;
cin.ignore();
name_of_vector.push_back(name_of_variable_type_struct);
}

c approach

to store struct in a vector you declare first the vector

 struct name_of_your_struct* name_of_vector=malloc(nsize_vector_chosen*sizeof(struct name_of_your_struct)); 

you fill your vector with the adequate informations (first example move-$100)

strcpy(name_of_vector[0].name,"move");
name_of_vector[0].price=100;

you can repeat that many times with a loop

i=0;
while(i<size_vector_chosen)
{
scanf("%s",string);
strcpy(name_of_vector[i].name,string);

scanf("%d",&price_number);
name_of_vector[i].price=price_number;
i++;
}

C - printf string with array of structures

In the best case you may get some random garbage. However, most likely your program will just segfault: Your codes declares id, but doesn't allocate space for it.

You need to declare it as

char id[IDLEN]

But then, the id you get when reading the file is a char* and the compiler will complain when trying to assign it to llegada[i].id.

For this to work, you need to make a string copy using the string.h library.

The following code works.

#include <stdio.h>
#include <string.h>
#define MAX 100
#define IDLEN 80
struct vehiculos{
float peso;
int hora;
char id[IDLEN];
int ferry;
};

void asignar(struct vehiculos llegada[MAX], FILE* input_file) { // Here i have more parameters, but they are useless in this question...
char id[IDLEN];
int i;
i=0;
while(!feof(input_file)){
fscanf(input_file,"%f %d %s %d",&llegada[i].peso,&llegada[i].hora,id,&llegada[i].ferry);
strcpy(llegada[i].id , id);
i++;
}
}

int main(){

struct vehiculos llegada[MAX];
FILE *entrada;
entrada = fopen("proy1.txt","r");
asignar(llegada,entrada);
printf("%s\n",llegada[0].id);

return 0;
}

Struct memory layout in C

In C, the compiler is allowed to dictate some alignment for every primitive type. Typically the alignment is the size of the type. But it's entirely implementation-specific.

Padding bytes are introduced so every object is properly aligned. Reordering is not allowed.

Possibly every remotely modern compiler implements #pragma pack which allows control over padding and leaves it to the programmer to comply with the ABI. (It is strictly nonstandard, though.)

From C99 §6.7.2.1:

12 Each non-bit-field member of a
structure or union object is aligned
in an implementation- defined manner
appropriate to its type.

13 Within a
structure object, the non-bit-field
members and the units in which
bit-fields reside have addresses that
increase in the order in which they
are declared. A pointer to a structure
object, suitably converted, points to
its initial member (or if that member
is a bit-field, then to the unit in
which it resides), and vice versa.
There may be unnamed padding within a
structure object, but not at its
beginning.



Related Topics



Leave a reply



Submit