cpp / beginner
Snippet
Structures: Grouping Related Data Together
A structure (struct) groups together different data types under one name. Think of it as a custom data type you define yourself. Each item in a struct is called a member. Here we create a Student struct with three members: name (string), age (int), and gpa (float). We then create a Student variable and access its members using the dot operator.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>#include <string>using namespace std;struct Student {string name;int age;float gpa;};int main() {Student s1;s1.name = "Alice";s1.age = 20;s1.gpa = 3.8f;cout << s1.name << " is " << s1.age << " years old" << endl;cout << "GPA: " << s1.gpa << endl;return 0;}
Breakdown
1
struct Student { ... };
Defines a new data type called Student with three members inside the curly braces
2
string name; int age; float gpa;
Three members of different types - name stores text, age stores whole numbers, gpa stores decimals
3
Student s1;
Creates a variable named s1 of type Student
4
s1.name = "Alice";
Accesses the name member of s1 and assigns the string "Alice" to it
5
s1.age = 20;
Sets the age member to 20
6
cout << s1.name
Uses dot operator (.) to access s1's name member for output