scanf函数学习

2018-03-20  本文已影响0人  排骨炖豆角不要豆角

scanf()函数是格式化读入屏幕的数据,该函数包含在头文件stdio.h中,一般形式为:
scanf("格式控制字符串", 地址列表);
其中地址列表就是使用 & 符号来提取变量在计算机中存储的位置id,在转而输入给scanf中的变量。

单个变量的输入

#include <stdio.h>
void main(void)
{
  int i_num=0;    /* 提前定义一个int变量,以便于后面的使用,否则会报错 */
  printf("\nPlz enter a number: \n");
  scanf("%d", &i_num);   /* &符号表示提取变量的存储位置id */
  printf("\nHaha, I have got the number %d\n",i_num);
}
使用上面的程序,输出为:

Plz enter a number: 
10

Haha, I have got the number 10

多个变量的输入

当输入多个变量时,可以使用下面的程序简单的达到目的:

#include <stdio.h>
void main(void)
{
  int a=0,b=0,c=0;
  printf("\nPlz enter a number: \n");
  scanf("%d%d%d", &a,&b,&c);   /* 注意这个里面三个%d格式化之间不存在任何的符号 */
  printf("\nHaha, I have got the number %d,%d,%d\n",a,b,c);
}

上面的函数中,可以使用如下的格式输入都是没有问题的:

Plz enter a number: 
12 15 13

Haha, I have got the number 12,15,13
Plz enter a number: 
12
12
15

Haha, I have got the number 12,12,15
Plz enter a number: 
15                 48                            
49

Haha, I have got the number 15,48,49

变量中间带有符号

#include <stdio.h>
void main(void)
{
  int a,b;
  printf("\nPlz enter a number: \n");
  scanf("%d,%d", &a,&b);   /* 注意是这个位置%d,%d之间存在一个逗号 */
  printf("\nHaha, I have got the number %d,%d\n",a,b);
}

那么上面的程序就是以逗号为分界的,结果如下:

Plz enter a number: 
1234,5
Haha, I have got the number 1234,5

如果是%3d,%3d这种情况,输入如下:

Plz enter a number: 
1234,5

Haha, I have got the number 123,0

可见,必须是第一个数字少于三位数才能接收到两个变量的值,否则,第二个数字为0、

特殊的,当scanf函数里面是 cui=%3d,feng=%3d 这样的时候,必须将前面的cui 和 feng也都要带上,否则是不会得到正确输入的:

#include <stdio.h>
void main(void)
{
  int a,b;
  printf("\nPlz enter a number: \n");
  scanf("cui=%3d,feng=%3d", &a,&b);   /* 注意这个语句的不同之处 */
  printf("\nHaha, I have got the number %d,%d\n",a,b);
}

输入的几种情况和结果如下:
方法1

Plz enter a number: 
123,456
Haha, I have got the number 0,0

方法2

Plz enter a number: 
cui=123
Haha, I have got the number 123,0

方法3

Plz enter a number: 
cui=123,feng=456
Haha, I have got the number 123,456

综合以上方面可以发现,方法3里面的方式是正确的,这样才能得到正确的输入的两个变量的值。

上一篇 下一篇

猜你喜欢

热点阅读