OpenSUSE

导航

一个简单的输入与输出人机交互程序

代码
 1  /*
 2 
 3   * 编译器:  VC++6.0
 4 
 5   * 类   型:  C语言
 6 
 7   */
 8 正确方法一:
 9 #include <stdio.h>
10 
11 int main(void)
12 {
13     char n[20];//声明一个char型的具有20个元素的数组,n为数组名,即数组的首地址。
14     char *name;//声明一个指向char型变量的指针变量,name是指针变量,'*'代表指针而不是指乘。
15     name = n;//将指针变量name指向数组名为n的数组首地址。
16     int age;//声明一个int型的变量。
17     scanf("%s %d",name,&age);//'%s'代表字符串格式,'%d'代表十进制格式,'&'代表取地址,'scanf(...);'代表标准输入函数,'&age'代表%d的输入数据存放到以age变量名称的内存地址中。
18     printf("my name is %s , and my age is %d !\n",name,age);
19     getchar();
20     return 0;
21 }
22 运行结果:
23 
24 
25 正确方法二:
26 #include <stdio.h>
27 
28 int main(void)
29 {
30     char name[20];
31     int age;
32     scanf("%s %d",name,&age);//此处使用输入字符数组name中,方法一中是输入指针变量name所指的数组中,还有两者'%s' and '%d'之间有空格,请注意。
33     printf("my name is %s , and my age is %d !\n",name,age);
34     getchar();
35     return 0;
36 }
37 运行结果:
38 
39 
40 正确方法三:
41 #include <stdio.h>
42 
43 int main(void)
44 {
45     char name[20];
46     int age;
47     scanf("%d,%s",&age,name);//'%d' and '%s'之间用逗号隔开,键入值是也要键入逗号,此处是先%d后%s,请注意与下面错误方法区别。
48     printf("my name is %s , and my age is %d !\n",name,age);
49     getchar();
50     return 0;
51 }
52 运行结果:
53 
54 
55 错误方法:
56 #include <stdio.h>
57 
58 int main(void)
59 {
60     char name[20];
61     int age;
62     scanf("%s,%d",name,&age);//此处之间是逗号(与上不同在顺序上),但是却是错误的结果,因为程序将结果中的键入的'OpenSUSE,100'当成一串字符串一起存入了name为数组首地址的20个字节单元中了,又由于字符串是以'\0'为标志结束字符串的,而上面方法一和方法二用空格却可以,大家自己思考这个问题?而age变量没有赋初值,故打印其值时不是预期想要的结果。
63     printf("my name is %s , and my age is %d !\n",name,age);
64     getchar();
65     return 0;
66 }
67 运行结果:
68 
69 
70 

 

posted on 2009-12-21 18:38  OpenSUSE  阅读(345)  评论(1编辑  收藏  举报