我怎样才能摆脱C语言中的while循环呢?

fafcakar  于 2023-03-17  发布在  其他
关注(0)|答案(2)|浏览(153)
#include <stdio.h>

int main() {
double a, b, c;
int total_Result;

    while(1) {
        printf("please enter 3 number\n");
        total_Result = scanf("%lf %lf %lf", &a, &b, &c);
        printf("totalresult = %d\n", total_Result);
    
        if(total_Result == 3) {
            
            printf("your numbers: a = %f, b = %f, c = %f\n", a, b, c);
            break;
        }
        else {
            puts("you should enter the number");
            
        }
    }
    
    return 0;

}

当我们不小心在上面的代码块中输入了字符串表达式而不是数字时,它会自动给出错误并进入无限循环。我如何在不使用任何新方法或函数的情况下解决这个问题呢?你有什么建议?
当我输入3个数字时,程序运行没有错误。但是,当我输入2个数字和1个字符时,它进入无限循环,我不希望这样。我希望他再检查一次数字。

c2e8gylq

c2e8gylq1#

您需要从输入缓冲区中删除无效数据。

while(1) {
    printf("please enter 3 number\n");
    total_Result = scanf("%lf %lf %lf", &a, &b, &c);
    printf("totalresult = %d\n", total_Result);

    if ( total_Result == EOF ) break;

    if(total_Result == 3) {
        
        printf("your numbers: a = %f, b = %f, c = %f\n", a, b, c);
        break;
    }
    else {
        scanf( "%*[^\n]" );
        puts("you should enter the number");
        
    }
}
rkttyhzu

rkttyhzu2#

检测到无效输入后清除输入缓冲器:

while(1) {
    printf("please enter 3 numbers\n");
    total_Result = scanf("%lf %lf %lf", &a, &b, &c);

    if(total_Result == 3) {
        printf("your numbers: a = %f, b = %f, c = %f\n", a, b, c);
        break;
    }
    else {
        puts("you should enter 3 numbers");
        while(getchar() != '\n'); // clear input buffer
    }
}

相关问题