1、通过strcpy函数将字符串复制过去
#include <stdio.h>
#include <string.h>
struct student{
char name[10];
};
int main (void)
{
struct student boy1;
strcpy (boy1.name, "Harry");
printf ("%s\n", boy1.name);
return 0;
}
使用这种方法需要注意的是:
(1)需要包含头文件<string.h>
(2)需要一个个进行赋值,比较麻烦
(3)在不同的编译器中对strcpy函数支持不同,比如vs2013就需要使用strcpy_s这个函数,此函数需要三个参数,中间需要加上一个复制字符串的长度。
2、定义结构体指针进行输入:
#include <stdio.h>
#include <malloc.h>
struct student{
char name[10];
};
int main (void)
{
struct student *p_boy1;
p_boy1 = (struct student *)malloc(sizeof (struct student));
printf ("Input your name:");
scanf ("%s", &p_boy1->name);
printf ("%s\n", p_boy1->name);
return 0;
}
使用这种方法需要注意的是:
(1)需要定义一个结构体指针,上边定义的是p_boy1这个指针;
(2)进行输入前需要先分配一个空间,上边使用malloc来完成;
(3)最后输入时需要取址符。
3、结构体中的共同体的字符串输入:
(1)首先,同样可以使用复制的方法输入,可参照如下代码:
#include <stdio.h>
#include <string.h>
struct student{
union {
char name[10];
}boy;
};
int main (void)
{
struct student boy1;
strcpy (boy1.boy.name, "Tom");
printf ("%s\n", boy1.boy.name);
return 0;
}
(2)通过键盘键入:
#include <stdio.h>
#include <malloc.h>
struct student{
union {
char name[10];
}boy;
};
int main (void)
{
struct student *p_boy1;
p_boy1 = (struct student *)malloc(sizeof (struct student));
printf ("Input your name:");
scanf ("%s", &p_boy1->boy.name);
printf ("%s\n", p_boy1->boy.name);
return 0;
}
注意事项参照第二点;
在调用共用体内容时,用’.'进行分隔。