C语言的scanf实现输入 详解笔记

时间:2025-02-23 14:08:53

C语言的scanf实现输入

    • scanf作用
    • scanf的规范点
    • 转换规范
    • 常见的输入错误
    • 实现整数的输入
    • 实现小数的输入
    • 实现字符输入
    • 字符串的输入
    • scanf与printf的不同

scanf作用

scanf将键盘输入的字符串根据转换规范,转换成二进制表示的整数、浮点数、字符或
字符串等。
根据用户的输入 赋值给程序的数据

举个例子

#include <>
int main()
{
   
	char c;
	short s;
	int n;
	long l;
	float f;
	double df;
	scanf("%hhd %hd %d %ld %f %lf", &c, &s, &n, &l, &f, &df);
	printf("%d %d %d %d %f %f\n", c, s, n, l, f, df);
	return 0;
}

运行程序后,在键盘输入:“11 22 33 42 5.6 71.8”。scanf函数,将字符串"1 2 3 4 5.6 7.8",根据转换规范,
分别转换为各类二进制数据,并存储到变量中

scanf的规范点

  1. scanf是一个变参函数。
scanf("%hhd %hd %d %ld %f %lf", &c, &s, &n, &l, &f, &df);
scanf("%d %ld %f %lf", &c,  &l, &f, &