相关疑难解决方法(0)

我可以用什么代替scanf进行输入转换?

我经常看到人们不鼓励其他人使用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

c scanf

124
推荐指数
7
解决办法
8381
查看次数

如何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)

怎么可以避免?

c scanf

11
推荐指数
4
解决办法
13万
查看次数

标签 统计

c ×2

scanf ×2