我经常看到人们不鼓励其他人使用scanf并说有更好的选择。但是,我最终看到的只是“不要使用scanf”或“这里是正确的格式字符串”,并且从来没有提到“更好的替代方案”的任何示例。
例如,让我们看一下这段代码:
scanf("%c", &c);
Run Code Online (Sandbox Code Playgroud)
这将读取最后一次转换后留在输入流中的空白。通常建议的解决方案是使用:
scanf(" %c", &c);
Run Code Online (Sandbox Code Playgroud)
还是不使用scanf。
由于scanf不好,用于转换scanf通常无需使用即可处理的输入格式(例如整数,浮点数和字符串)的ANSI C选项有哪些scanf?
我希望代码运行,直到用户输入整数值.
该代码适用于char和char数组.
我做了以下事情:
#include<stdio.h>
int main()
{
int n;
printf("Please enter an integer: ");
while(scanf("%d",&n) != 1)
{
printf("Please enter an integer: ");
while(getchar() != '\n');
}
printf("You entered: %d\n",n);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
问题是如果用户输入一个浮点值scanf就会接受它.
Please enter an integer: abcd
Please enter an integer: a
Please enter an integer: 5.9
You entered: 5
Run Code Online (Sandbox Code Playgroud)
怎么可以避免?