C语言中使用scanf的一些注意事项

(1)scanf读取double类型数据应该使用%lf;而使用printf打印double时,要注意%lf用在printf中是C99才支持的,因此如果编译器不支持C99则要使用%f

double d;
scanf("%lf", &d);
printf("%f", d);

参考资料:
Reading in double values with scanf in c
Why does scanf() need “%lf” for doubles, when printf() is okay with just “%f”?

(2)

char str[10];
scanf ("%[^\n]%*c", str);

%[^\n]含义是从stdin读取输入保存到str,直到遇到第一个\n;而%*c则丢弃掉这个\n
参考资料:
scanf: “%[^\n]” skips the 2nd input but “ %[^\n]” does not. why?
What does scanf(“%*[^\n]%*c”) mean?

(3)限制输入字符串的长度,预留结尾的NUL

char str[10]
scanf("%9s", str);