(JohnZero)C++:struct typedef enum

结构体struct

声明并初始化结构体

#include<iostream>
using namespace std;
struct student
{
    int num;    //学号
    char name[20];  //姓名
    char sex;   //性别
    int age;    //  年龄
}stu = {123456,"John Zero",'M',19};
int main()
{
    cout << stu.num << endl;
    cout << stu.name << endl;
    cout << stu.sex << endl;
    cout << stu.age << endl;
}

在这里插入图片描述

如何为结构体中的字符数组赋值

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

struct happy
{
    char me[10];
};

int main()
{
happy h;
strcpy(h.me, "hello");
printf("%s", h.me);
}

如果要用户输入:

int main()
{
happy h;
scanf("%s", &h.me[0]);
printf("%s", h.me);
}

可以在结构体声明时直接赋值,这样char me[]的中括号内不需要填,否则必须声明字符数组大小,否则就是没有大小的字符数组,当然不能放进去值

你想要用户自己输入可以用

struct MyStruct
{
    char me[80];
};

#include <iostream>
using namespace std;
int main() {
    MyStruct * my = new MyStruct();
    char d;
    for (int i = 0; i < 80; i++) {
        cin.get(d);
        my->me[i] = d;
        if (d == '\n') {
            break;
        }
    }
    return 0;
}

自包含

#include<iostream>
#include<vector>
using namespace std;

struct ListNode {
 int val;
 ListNode *next;
 ListNode(int x) : val(x), next(NULL) {}
};

int main()
{
 ListNode *p = new ListNode(1);
 p->next = new ListNode(2);
 cout << p->val << endl;
 cout << p->next->val << endl;
 ListNode* q = p; //引用
 q->val = 3;
 q->next->val = 8;
 cout << p->val << endl;
 cout << p->next->val << endl;
}

输出结果:
在这里插入图片描述
用vector初始化链表

struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
};

vector<int>vec = { 1,2,3,4,5 };
ListNode* head = new ListNode(vec.front());
ListNode* node = head;
for (int i = 1; i < vec.size(); i++)
{
    node->next = new ListNode(vec[i]);
    node = node->next;
}
for (int i = 0; i < vec.size(); i++)
{
    cout << head->val << ' ';
    head = head->next;
}

在这里插入图片描述

LeetCode:
21.合并两个有序链表

自定义数据类型typedef

typedef int age, grade;
typedef double height, weight;
age a1 = 16, a2 = 19;
height h1 = 175.3, h2 = 182.6;
cout << a1 << ' ' << h1 << ' ' << a2 << ' ' << h2;

输出结果:
16 175.3 19 182.6

枚举类型enum

enum weekday{sun=7,mon=1,tue,wed,thu,fri,sat};
int main()
{
 enum gameResult{win,lose,tie,cancel};
 gameResult result, omit = cancel;
 for (int i = win; i <= cancel; ++i)
 {
  result = (gameResult)i;
  if (result == omit)
   cout << "游戏取消";
 }
}

输出结果:
游戏取消

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值