我应该在哪里放置我的验证码以供用户输入

时间:2015-12-07 12:06:21

标签: c if-statement

if (!strcmp(yn, "y")) {
  isCooked[x] = 1;
  printf("How much %s (in grams) will you cook? ", food[choice - 1]);
} else {
  isCooked[x] = 0;
  printf("How much %s (in grams) will you eat raw? ", food[choice - 1]);
}

scanf("%f", &grams);
userGrams[x] = grams;

如果我想控制克的用户输入,我应该把if-else语句放在哪里?我想对我的程序施加限制,比如用户应该只输入最小20g和最大200g。

1 个答案:

答案 0 :(得分:0)

您可以使用while循环和if语句 -

while(scanf("%f", &grams)==1){           // loop until scanf returns 1 
    if(grams>=20 && grams<=200){         // validate your input
        userGrams[x] = grams;            //assign value
        break;                           //break out of loop
    } 
   else{
        printf("Invalid Input !! ");
    }
}