Think about "struct
" keyword in C++ as a tool that will help us to create something that look alike small databases.
You probably used Excel or MySQL or any table preparation program where cells are used to store individual values.
Every intersection of a row and column in some table uniquely identify some value there.
So, while using "struct
" we are actually defining columns and in those columns we must put only values of specific data type.
For example, we are creating structure that will hold data about Books - that will be name of our structure.
In it we will have Title of the Book, Author, Topic and ID of a book if we have a small library.
All those values are of dedicated data type. When dealing with char data type we will state how big thay can possibly be:
struct Books {
char Title[50];
char Author[50];
char Topic[100];
int id_book;
};
All of that will be done outside main() section.
Inside main() section we will create first entry (think about it as table row) based on our struct Book. Name of first entry/row will be Book_1:
struct Books Book_1;
To get data in individual "cells" we will use strcpy method to copy string (concatenated characters) to specific column:
strcpy(Book_1.Title, "Relativity T");
strcpy(Book_1.Author, "Albert E");
strcpy(Book_1.Topic, "Relativity");
We don't need to use strcpy method on integers:
Book_1.id_book = 4323;
To have strcpy() function working we must have this line at the top of our program:
#include <cstring>
Full source:
#include <iostream>
#include <cstring>
using namespace std;
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;
return 0;
}
Result:
Process returned 0 (0x0) execution time : 0.064 s
Press any key to continue.
Excellent. In next tutorial we will extract and use data from our simple "database".
No comments:
Post a Comment