cpp / beginner
Snippet
Structs: Creating Custom Data Types
A struct (structure) lets you combine different data types into a single custom type. It's useful for grouping related data like a student's information. You can access struct members using the dot operator (.). Structs are the foundation for more complex data organization in C++.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>#include <string>using namespace std;struct Student {string name;int age;float gpa;};int main() {Student s1;s1.name = "Maria";s1.age = 20;s1.gpa = 3.8;Student s2 = {"Max", 22, 3.5};cout << s1.name << " ist " << s1.age << " Jahre alt." << endl;cout << s2.name << " hat einen GPA von " << s2.gpa << endl;return 0;}
Breakdown
1
struct Student { ... };
Defines a custom structure called Student with three members
2
Student s1;
Creates an instance 's1' of the Student struct
3
s1.name = "Maria";
Assigns a value to the 'name' member using the dot operator
4
Student s2 = {"Max", 22, 3.5};
Initializes a struct with values in curly braces