c - 如何循环 scanf_s() 直到成功?

标签 c loops while-loop format

#include <stdio.h>

int main(){

    float x,y;

    printf("Enter 2 numbers: \n");
    scanf_s("%f %f", &x, &y);

    if (getchar() == '\n')
    {
    printf("Division: %f\n", x / y);
    printf("Product: %f\n", x * y);
    printf("Sum: %f\n", x + y);
    printf("Difference: %f\n", x - y);
    }
    else
    {
        printf("no Float-Value!");
    }

getchar();
return 0;
}

我们需要一个循环,这样如果我们输入错误的格式,程序应该再次要求输入两个数字

最佳答案

检查输入有效性的最佳方法是检查 scanf_s 的返回值,它告诉您已成功设置的变量数。在你的情况下,如果它是 2 那么一切都很好;否则你需要重复。

换句话说

do {
    int c;
    while ((c = getchar()) != '\n' && c != EOF); // clear the input stream
    printf("Enter 2 numbers: \n");
} while (scanf_s("%f %f", &x, &y) != 2);

是一个合适的控制结构,而不是 if (getchar() == '\n'),您应该删除它。

关于c - 如何循环 scanf_s() 直到成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50840130/

相关文章:

c - 实现桶排序 - 使用 calloc 获得更好的性能?

arrays - 通过结构访问数组(使用指针)

c - 为什么指向 16 位寄存器的指针是 uword?

java - 如何增加使用 for 循环创建的 jlabel 变量名称?

python - 如何在我的第一个 python 计算器中修复这个 while 循环?

c - 路径:在 `#include` 中是否有效?

css - 响应式字体媒体查询少循环

C - 循环不继续

node.js - 如何防止 while 循环卡住 node.js?

java - 为什么第二次运行后才出现 "Try a higher/lower number."?