C语言学习【scanf函数】
scanf()
函数把输入的字符串转换成整数、浮点数、字符或字符串;
printf()
函数把整数、浮点数、字符和字符串转换成显示在屏幕上的文本;
scanf()
函数使用指向变量的指针;
printf()
函数使用变量、常量和表达式.
scanf函数两条简单的规则
- 如果用
scanf()
函数读取基本变量类型的值,在变量名前加上一个&
; - 如果用
scanf()
函数把字符串读入字符数组中,不要使用&
.
/* 何时使用& */
#include "stdio.h"
int main(void)
{
int age; /* 变量 */
float assets; /* 变量 */
char pet[30]; /* 字符数组 用于储存字符串 */
printf("Enter your age, assets, and favorite pet.\n");
scanf("%d %f", &age, &assets);
scanf("%s", pet);
printf("%d $%.2f %s\n", age, assets, pet);
}
程序运行结果
Enter your age, assets, and favorite pet.
22
1000
dog
22 $1000.00 dog
scanf()
函数使用空白(换行符、制表符和空格)把输入分成多个字段
以下为ANSI中scanf()
函数的转换说明
如果要使用多个修饰符,必须按照以下顺序书写
scanf()
函数允许把普通字符放在格式字符串中,除空格字符外的普通字符必须与输入字符串严格匹配,如下所示
/* 格式字符串中的普通字符 */
#include "stdio.h"
int main(void)
{
int m, n;
printf("请输入两个整数,并用英文逗号分隔");
scanf("%d, %d" ,&m, &n);
printf("m = %d, n = %d", m, n);
}
程序运行结果
请输入两个整数,并用英文逗号分隔12, 13
m = 12, n = 13
下面这样的输入格式也都是没有问题的
12, 13
12 , 13
12, 13
除%c
外,其他转换说明都会自动跳过待输入值前面的所有空白;
如果把%c
放在格式字符串中的空格前面,scanf()
便会跳过空格,从第一个非空白字符开始读取,如下所示
scanf("%c", &ch); /* 从输入的第一个字符开始读取 */
scanf(" %c", &ch); /* 从第一个非空白字符读取 */
/* @Last Modified Time: 2024-05-17 11:51:09 */
scanf()函数的返回值
scanf()
返回成功读取的项数;
如果没有读取任何项,且需要读取一个数字而用户却输入一个非数值字符串,scanf()
便返回0;
printf()和scanf()的*修饰符
*
修饰符代替字段宽度
/* 使用变宽输出字段 */
#include "stdio.h"
int main(void)
{
unsigned width, precision;
int number = 256;
double weight = 242.5;
printf("Enter a field width:\n");
scanf("%d", &width);
printf("The number is :%*d\n", width, number);
printf("Now enter a width and a precision:\n");
scanf("%d %d", &width, &precision);
printf("Weight = %*.*f\n", width, precision, weight);
printf("Done!\n");
return 0;
}
程序运行结果
Enter a field width:
6
The number is : 256
Now enter a width and a precision:
8 3
Weight = 242.500
Done!
在上述程序中,用户首先输入6
,因此,6
是程序使用的字段宽度;
类似地,接下来用户输入8和3,说明字段宽度是8,小数点后面显示3位数字.
scanf()
中*
的用法与此不同,把*
放在%
和转换字符之间时,会使得scanf()
跳过相应的输出项
/* 跳过输入中的前两个整数 */
#include "stdio.h"
int main(void)
{
int n;
printf("Please enter three integers:\n");
scanf("%*d %*d %d", &n);
printf("The last integer was %d\n", n);
return 0;
}
程序运行结果
Please enter three integers:
1 2 3
The last integer was 3
scanf()
根据不同的转换说明转换
/* scanf()函数 */
#include "stdio.h"
int main(void)
{
int string_d;
float string_f;
char string_s[40];
char string_c[40];
scanf("%d", &string_d);
printf("%d\n", string_d);
printf("\n");
scanf("%f", &string_f);
printf("%f\n", string_f);
}
程序运行结果
12.45# 0
12
0.450000
假设有如下输入行: -13.45e12# 0
如果其对应的转换说明是%d
,scanf()
会读取3
个字符(-13)并停在小数点处,小数点将被留在输入中作为下一次输入的首字符;
如果其对应的转换说明是%f
,scanf()
会读取-13.45e12
,并停在#
符号处,而#
将被留在输入中作为下一次输入的首字符;然后,scanf()把读取的字符序列-13.45e12 转换成相应的浮点值,并储存在float类型的目标变量中。
如果其对应的转换说明是%s
,scanf()
会读取 -13.45e12#
,并停在空格处,空格将被留在输入中作为下一次输入的首字符;然后,scanf()
把这10个字符的字符码储存在目标字符数组中,并在末尾加上一个空字符。
如果其对应的转换说明是%c,scanf()
只会读取并储存第1个字符,该例中是一个空格.