| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1096 人关注过本帖
标题:共用体不是只能存一个数吗,这个怎么能存两个?
只看楼主 加入收藏
see235959850
Rank: 2
等 级:论坛游民
帖 子:380
专家分:29
注 册:2016-12-21
结帖率:100%
收藏
 问题点数:0 回复次数:2 
共用体不是只能存一个数吗,这个怎么能存两个?
程序代码:
#include<stdio.h>
struct
{
    int num;
    char name[10];
    char sex;
    char job;
    union
    {
        int clas;
        char position[10];
    }category;
}person[2];

int main()
{
    int i;
    for (i = 0; i < 2; i++)
    {
        printf("Please enter the data of person:\n");
        scanf_s("%d %s %c %c", &person[i].num, &person[i].name, 10, &person[i].sex, 1, &person[i].job, 1);
        if (person[i].job == 's')
            scanf_s("%d", &person[i].category.clas);
        else if (person[i].job == 't')
            scanf_s("%s", &person[i].category.position, 10);
        else
            printf("Input error!");
    }
    printf("\n");
    printf("No.    name    sex job class/position:\n");
    for (i = 0; i < 2; i++)
    {
        if (person[i].job == 's')
            printf("%d %7s %6c %3c %7d\n", person[i].num, person[i].name, person[i].sex, person[i].job, person[i].category.clas);
        else
            printf("%d %7s %6c %3c %7s\n", person[i].num, person[i].name, person[i].sex, person[i].job, person[i].category.position);
    }
    return 0;
}
2017-02-04 09:10
linlulu001
Rank: 13Rank: 13Rank: 13Rank: 13
等 级:贵宾
威 望:20
帖 子:944
专家分:4047
注 册:2016-4-13
收藏
得分:0 
没有存两个,只是选择存入两个中的一个。
if (person[i].job == 's')
            scanf_s("%d", &person[i].category.clas);
else if (person[i].job == 't')
            scanf_s("%s", &person[i].category.position, 10);
else
            printf("Input error!");
共用体存入的信息是根据job来选择的,所以你说存入两组数据不存在,只存入一组。

[此贴子已经被作者于2017-2-4 09:17编辑过]

2017-02-04 09:15
see235959850
Rank: 2
等 级:论坛游民
帖 子:380
专家分:29
注 册:2016-12-21
收藏
得分:0 
回复 2楼 linlulu001
谢谢
2017-02-04 09:33
快速回复:共用体不是只能存一个数吗,这个怎么能存两个?
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.021485 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved