【问题标题】:How do I re enter an integer value in a 'while' loop?如何在“while”循环中重新输入整数值?
【发布时间】:2016-03-12 10:04:41
【问题描述】:
printf("please enter a value for side a: ");
check1 = scanf(" %d*%c", &a);
while(check1 != 1)
    {
    printf("You have entered an invalid value");
    scanf(" %d*%c", &a);
    }
printf("The value for A is: %d\n", a);

我试图确保输入的值是一个整数,只有 (check1 != 1)。如果我输入除整数以外的任何内容并且 while 循环启动,它会无限打印“您输入的值无效”,但会忽略 scanf 以重新输入 A 的值。

我在此之前写了一段代码,它没有 (check != 1) 部分,但在 while 循环中有一个 scanf 有效。

printf("\nEnter the denominator number: ");
scanf("%d%*c", &num2);
while ( num2 <= 0 )
    {
    printf("The denominator can not be 0 or less, re enter the number: ");
    scanf("%d%*c", &num2);
    }

注意第二个代码块有效。

我该如何解决这个问题?或者有人可以提出一个简单的替代方法来确保“a”是一个整数?我对编程很陌生,scanf 是我知道的唯一输入提示。

非常感谢您的帮助:)

【问题讨论】:

    标签: c scanf


    【解决方案1】:

    在 while 循环中,您需要在使用 'scanf' 函数后更改 'check1' 的值。

    int a; char* w;
    printf("please enter a value for side a: ");
    int check1 = scanf(" %d*%c", &a);
    while (check1 != 1)
    {
        scanf("%s", &w);
        printf("You have entered an invalid value\nplease enter a value for side a: ");
        check1 = scanf(" %d*%c", &a);
    }
    printf("The value for A is: %d\n", a);
    

    【讨论】:

    • 我要把这个值改成什么?我试着做 "check1 = scanf(" %d*%c", &a);"在while循环内无济于事-对不起代码!
    • @Josh,请不要在 cmets 中发布代码。不可读。
    • 谢谢你,这正是我所需要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多