Menu
Coddy logo textTech

Skrócona składnia

Lekcja 4 z 8 w kursie Struktury w C/C++ w Coddy.

Można również przypisać wartości składowym zmiennej struktury w momencie deklaracji, w jednym wierszu.

Wstaw wartości w postaci listy oddzielonej przecinkami wewnątrz nawiasów klamrowych {}; kolejność ma znaczenie!

#include <iostream>
#include <string>

struct Student {
    int roll_number;
    std::string name;
    float marks;
};

int main() {
    Student student1 = {101, "Alice", 85.5};
    std::cout << "Roll Number: " << student1.roll_number << std::endl;
    std::cout << "Name: " << student1.name << std::endl;
    std::cout << "Marks: " << student1.marks << std::endl;
    return 0;
}

Albo w C (zauważ, że nie musisz używać metody strcpy)

#include <stdio.h>

struct Student {
    int roll_number;
    char name[50];
    float marks;
};

int main() {
  struct Student student1 = {101, "Alice", 85.5};
  printf("Roll Number: %d\nName: %s\nMarks: %.2f\n", student1.roll_number, student1.name, student1.marks);
  return 0;
}
challenge icon

Wyzwanie

Łatwy

Utwórz strukturę Employee, która będzie przechowywać imię i nazwisko pracownika (string), jego identyfikator (int) oraz wynagrodzenie (float).

Następnie zainicjalizuj trzech pracowników i wyświetl ich wartości w formacie:

 ID: {id}, Name: {name}, Salary: {salary}

Spróbuj swoich sił

#include <stdio.h>
#include <string.h>

int main() {
    // Wpisz kod tutaj
    return 0;
};

Wszystkie lekcje w sekcji Struktury w C/C++

Poćwicz samodzielnie: Kompilator C online