Saturday, April 19, 2025

C++ Passing Struct to Function

To have a generic solution how to get data from our Book structure we will create a function that will accept any concrete structure as parameter.

Data type must be struct, and all those "columns" must be replaced with a generic column, in this case "genField":

void getStuff(struct Books genField) {

    cout << "Book_1 - Title:  \t" << genField.Title   << endl;
    cout << "Book_1 - Author: \t" << genField.Author  << endl;
    cout << "Book_1 - Topic:  \t" << genField.Topic   << endl;
    cout << "Book_1 - ID:     \t" << genField.id_book << endl;

    cout << "-------------------------------------" << endl;

}

Of course, function must be used inside main() section where we will provide Book_1 as argument:

getStuff(Book_1);

Full source: 

#include <iostream>
#include <cstring>

using namespace std;

void getStuff(struct Books genField);

struct Books {
    char Title[50];
    char Author[50];
    char Topic[100];
    int id_book;
};

int main() {

    struct Books Book_1;

    strcpy(Book_1.Title, "Relativity T");
    strcpy(Book_1.Author, "Albert E");
    strcpy(Book_1.Topic, "Relativity");
    Book_1.id_book = 4323;

    getStuff(Book_1);

    return 0;

}

void getStuff(struct Books genField) {

    cout << "Book_1 - Title:  \t" << genField.Title   << endl;
    cout << "Book_1 - Author: \t" << genField.Author  << endl;
    cout << "Book_1 - Topic:  \t" << genField.Topic   << endl;
    cout << "Book_1 - ID:     \t" << genField.id_book << endl;

    cout << "-------------------------------------" << endl;

}

Result:

Book_1 - Title:         Relativity T
Book_1 - Author:        Albert E
Book_1 - Topic:         Relativity
Book_1 - ID:            4323
-------------------------------------

Process returned 0 (0x0)   execution time : 0.124 s
Press any key to continue.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...