C语言实例1

时间:2023-01-13 15:57:12

  用户输入数据,并回显的案例 :

#include <stdio.h>

int main() {
char ch;
while((ch = getchar()) != '#') {
putchar(ch);
}
printf("done");
return 0;
}

 

  读取文件,并输出内容 : 

#include <stdio.h>
#include <stdlib.h>

int main() {
FILE *f;
char fname[50];
int str;
printf("input file name to read : ");
scanf("%s", fname);
f = fopen(fname, "r");
if( f == NULL ) {
printf("failed to open the file");
exit(0);
}
while((str = getc(f)) != EOF) {
printf("%c",str);
putchar(str);
}
return 0;
}

 

   union共用体, 只会实时保存一种类型 :

#include <stdio.h>

union variant /* 定义一个共用体类型*/
{
char c; /* 字符型成员 */
int i; /* 整型成员 */
};
union variant x; /* 定义共用体变量,这里定义为全局变量,所以变量的全部字节的初值都为0 */
int main() {
x.c='A'; /* 为共用体变量中的字符型成员赋值 */
printf("%d\n",x.i); /* 此时共用体变量4个字节的取值情况为0x00000041 */
x.i=0xFFFFFF42; /* 为共用体变量中的整型成员赋值,0x42为字母B的ASCII码*/
printf("%c\n",x.c);
return 0;
}

  枚举类型 , 初始化枚举类型以后 , 枚举类型的值从0, 开始递增+1:

#include <stdio.h>

enum week /* 定义一个枚举类型 */
{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
};
int main()
{
enum week a, b; /* 定义一个枚举变量 */
a=TUESDAY; /* 枚举常量TUESDAY的值为2 */
b=THURSDAY; /* 枚举常量THURSDAY的值为4 */
int c=6;
printf ("a = %d\nb = %d\nc = %d\n",a,b,c); /* 输出枚举变量和整型变量的值 */
return 0;
}

   获取用户输入的实例 : 

#include <stdio.h>
#define MAXTITL 41
#define MAXAUTL 31

struct book {
char title[MAXTITL];
char author[MAXAUTL];
float value;
};
int main () {
struct book library;
printf("enter the book title : \n");
gets(library.title);
printf("enter the author : \n");
gets(library.author);
printf("enter the value : \n");
scanf("%f", &library.value);
printf("%s, %s, %f", library.title, library.author, library.value);
return 0;
}

天道酬勤