如何防止scanf失败的无限循环

时间:2015-09-15 19:51:02

标签: c loops scanf

本守则应该换一美元并且运作良好。但是教授说他会随信输入随机数字。它可以正常使用数字,但是当输入一个字母时,会出现无限循环的任何建议吗?

#include <stdio.h>
#include <stdlib.h>
#define amtPaid 1
#define SENTINAL -1
int quarters(int numChange);
int dimes(int numChange);
int nickels(int numChange);
int pennies(int numChange);

int main(void)
{
    double amtDue = 0; // how much is paid


while(1){
    printf("\nPlease enter the price less than 1 dollar: ");
    scanf(" %lg", &amtDue);
    int changeReturn = (amtPaid - amtDue) * 100 + 0.5; // convert decimal to whole number
    int updated = 0;    // remaining change after amt of change
    int numberQuarters = quarters(changeReturn); // number of quarters needed

   if(changeReturn >= 0 && changeReturn <= 100){ // if changereturn  is between 0 and 100 execute code

        printf("\nNice!");
        printf("\nWe owe you %i cents" , changeReturn);
        if(numberQuarters >= 0){    // get and print number of quarters
            printf("\nQuarters: %i", numberQuarters);
            updated = changeReturn % 25;
        }
        if(dimes(updated) >= 0){ // get and print number of dimes
            printf("\nDimes: %i", dimes(updated));
            updated = updated % 10;
        }
        if(nickels(updated)>= 0){ // get and print number of nickels
            printf("\nNickels: %i", nickels(updated));
            updated = updated % 5;
        }
        if(pennies(updated) >= 0){ // get and print number pennies
            printf("\nPennies: %i", pennies(updated));
        }

    }

    else if(amtDue == SENTINAL){
        break;
    }

    else {
        printf("That does not make sense to me. please type a valid number");
    }

    printf("\n %g", amtDue);

}
return 0;
}

int quarters(int numChange){
    int numQuarters = 0;

    numQuarters = numChange / 25;

    return numQuarters;
}
int dimes(int numChange){
    int numDimes = 0;

    numDimes = numChange / 10;

    return numDimes;
}
int nickels(numChange){
    int numNickels = 0;

    numNickels = numChange / 5;

    return numNickels;
}
int pennies(numChange){

    return numChange;
}

2 个答案:

答案 0 :(得分:3)

如果提供的格式说明符与scanf()的预期值不同,则提供的值不合适,scanf()将失败,输入中的将保留缓冲区,将 feed 提供给下一个scanf(),仅导致连续失败。在这种情况下,您需要在进行下一次输入之前清理输入缓冲区。你可以使用像

这样的东西
  1. 检查scanf()
  2. 的返回值
  3. 如果失败,请使用while( getchar() != '\n' );清除输入缓冲区。
  4. 也就是说,int nickels(numChange) cC99以后int现在无效。您必须明确地将其设为CKM_AES_CTR

答案 1 :(得分:0)

不是使用scanf(" %lg", &amtDue);,而是将用户输入作为字符串,这样您就可以进行适当的检查。

char input[500];
fgets(input, 500, stdin);

// do some input checking

double val = atof(input);

// do calculations on the number

要查看,ctype.h中有各种各样的功能可以帮助您,您可能会感到有趣的是isalpha

<小时/>

手动参考: