如何循环scanf_s()直到成功? [英] How to loop scanf_s() until success?

查看:118
本文介绍了如何循环scanf_s()直到成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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;
}

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

we need to get a loop in so if we enter the wrong format the program should ask again to enter two numbers

推荐答案

检查输入有效性的最好方法是检查scanf_s的返回值,该值告诉您成功设置的变量数.在您的情况下,如果为2,则一切正常;否则为0.否则,您需要重复.

The best way of checking the validity of the input is to check the return value of scanf_s which tells you the number of variables that were successfully set. In your case, if it's 2 then all is well; otherwise you need to repeat.

换句话说

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').

is an appropriate control structure, rather than if (getchar() == '\n'), which you should drop.

这篇关于如何循环scanf_s()直到成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆