进度日志30 (条件编译,结构体(变量初始化、数组、指向结构体类型数据的指针))
学习笔记1:条件编译
#include <stdio.h>
#define CORRECT "Why"
void main()
{
char str[40]; //定义一个字符串变量来让用户输入字符串
int cmp(char *str1, char *str2); //自己定义一个对比函数,将用户输入的字符串跟标准的COTTECT进行对比
printf("Don't get jealous of me.\n ");
loop:gets(str); //可以接收开空格的字符串,回车则结束输入
#ifndef CORRECT //如果这里没定义宏名
#define CORRECT "Why" //就在这里定义一下
#endif
if (cmp(str, CORRECT) == 0) //在这里进行比较,如果输入的字符串包含COTTECT......
{
printf("\nBecause I worked my ass off to get it.\nNobody handed me nothing.\n");
}
else
{
printf("\nI live richer, better and more enjoyable than you. If you ask me why, I can tell you.\n");
goto loop;
}
}
int cmp(char *str1, char *str2) //在这里定义函数的具体内容
{
int i = 0, j = 0;
while (str1[i])
{
while (str2[j] == str1[i])
{
i++;
j++;
if (!str2[j])
{
return 0;
}
}
j = 0;
i++;
}
return -1;
}
运行结果1:
运行结果2:
学习笔记2:结构体 (关于结构体,详见笔记本)
编程1:结构体变量初始化
#include <stdio.h>
void main()
{
struct student //定义结构
{
int num;
char *name;
char sex;
float score;
}boy1, boy2 = {102,"Jame","H",98.5};
boy1 = boy2;
printf("Number=%d\nName=%s\nScore=%f\n\n\n", boy1.num, boy1.name, boy1.score);
printf("Number=%d\nName=%s\nScore=%f\n\n\n", boy2.num, boy2.name, boy2.score);
}
运行结果:
编程2:用结构体数组建立通讯录
#include <stdio.h>
#include <stdlib.h>
#define NUM 3
struct person
{
char name[20];
char phone[10];
};
void main()
{
struct person man[NUM];
int i;
printf("new friend\n\n");
for (i = 0; i < NUM; i++)
{
printf("name:\n");
gets(man[i].name);
printf("phone:\n");
gets(man[i].phone);
}
printf("\t\tname\t\t\t\t\tphone\n\n");
for (i = 0; i < NUM; i++)
{
printf("%20s\t\t\t%20s\n", man[i].name, man[i].phone);
}
system("pause");
}
运行结果:
编程3:指向结构体类型数据的指针
#include <stdio.h>
struct stu
{
int num;
char *name;
char sex;
float score;
}boy1 = { 102,"King",'M',78.5 }; //赋初值
void main()
{
struct stu *pstu; //定义结构变量指针
pstu = &boy1; //把boy1的初始值给他,注意不能把结构名给他
//通过以下三种形式输出
printf("Number= %d\nName= %s\n", boy1.num, boy1.name);
printf("Sex= %c\nScore= %f\n\n", boy1.sex, boy1.score);
printf("Number= %d\nName= %s\n", (*pstu).num, (*pstu).name);
printf("Sex= %c\nScore= %f\n\n", (*pstu).sex, (*pstu).score);
printf("Number= %d\nName= %s\n", pstu->num, pstu->name);
printf("Sex= %c\nScore= %f\n\n", pstu->sex, pstu->score);
}
运行结果: