在C输入验证 [英] Input validation in C

查看:153
本文介绍了在C输入验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C编写程序在程序中,用户必须选择一个数,是1,2或3。我想构造code,这样,当用户在多个进入这不是1,2或3时,他/她会被告知无效的选择 - 再次选择,然后他们将被带回程序的启动:

I'm writing a program in C. In the program, the user has to choose a number, either 1, 2 or 3. I would like to construct the code so that when the user enters in a number that isn't 1, 2 or 3, he/she will be told "Invalid selection - choose again" and then they will be brought back to the start of the program:

int main() {

    int choice;
    char response, Y, N;

    printf("Choose a shape from the following:\n 1.Sphere\n 2.Cone\n 3.Cylinder\n");

    scanf("%d",&choice);

    if(choice==1||choice==2||choice==3) {
        printf("Enter the radius, r\n");                             
    } else
        printf("Invalid selection, choose again.\n");

}

我想的是,经过无效的选择,再次选择出现时,用户带回程序的开始,这样他们就可以重新输入他们的选择。我会怎么做呢?

What I would like is that after "Invalid selection, choose again" appears, the user is brought back to the start of the program, so they can input their choice again. How would I do this?

推荐答案

下面就是你要做的:

int choice;
char response, Y, N;
for (;;) {
    printf("Choose a shape from the following:\n 1.Sphere\n 2.Cone\n 3.Cylinder\n");

    scanf("%d",&choice);

    if(choice==1||choice==2||choice==3) {
        break;                    
    }
    printf("Invalid selection, choose again.\n");
}

一旦这个循环结束,提示半径。您将几乎肯定需要另一个循环至prevent负值为半径的投入,所以在同一回路不提示它。

Once this loop is over, prompt for the radius. You will nearly certainly need another loop to prevent the input of negative values for the radius, so do not prompt for it in the same loop.

这篇关于在C输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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