Menu
Coddy logo textTech

Short Syntax

Coddy의 C/C++ 구조체 코스 레슨 — 8개 중 4번째.

구조체 변수를 선언할 때 한 줄로 멤버에 값을 할당하는 것도 가능합니다.

중괄호 {} 안에 쉼표로 구분된 목록으로 값을 삽입하세요. 순서가 중요합니다!

#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;
}

또는 C 언어에서는 (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

챌린지

쉬움

이름(string), id(int) 및 급여(float)를 저장하는 Employee 구조체를 생성하세요.

그 후, 세 명의 직원을 초기화하고 다음 형식으로 값을 출력하세요:

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

직접 해보기

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

int main() {
    // 여기에 코드를 작성하세요
    return 0;
};

C/C++ 구조체의 모든 레슨