做到这一点,以便在输入无效值时,用户必须在C中重试新值 [英] make it so when an invalid value is inputted the user must retry a new value in C

查看:77
本文介绍了做到这一点,以便在输入无效值时,用户必须在C中重试新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的硬件分配,我必须创建一个程序,该程序输出取决于用户输入的基于星号的三角形.我已经使程序在用户输入整数时可以正常工作,但是输出的是正确的三角形,但是我的问题是,当输入无效值时,我该如何设置它,以便用户必须再次尝试提交值?我查看了论坛,但找不到类似的问题.

For my HW assignment I have to create a program that outputs an asterisk based triangle that depends on user input. I have gotten my program to work as far as when the user inputs an integer the correct triangle is outputted, but my issue is when an invalid value is inputted how do I make it so that the user must re-attempt to submit a value? I looked on the forums and I have not been able to find a similar question.

#include <stdio.h>

int main() {
int lines, a, b;

//prompt user to input integer
printf("Input a value from 1 to 15: ");
scanf("%d", &lines);

//Check if inputed value is valid
if(lines >= 1 && lines <= 15) {
    /*create triangle based on inputed value */
    for(a = 1; a <= lines; a++) {
        for(b=1; b<= a; b++) {
            printf("*");
        }
        printf("\n");
    }
}
else {
    printf("not valid");/* repeat code in this else statement, maybe */
}
system("pause");
}

推荐答案

#include <stdio.h>

int main() {
int lines, a, b;

//prompt user to input integer
do{
    printf("Input a value from 1 to 15: ");
    scanf("%d", &lines);

    //Check if inputed value is valid
    if(lines < 1 || lines > 15) {
        printf("Error: Please Enter a Valid number!!!\n");
        continue;
    }
    /*create triangle based on inputed value */
        for(a = 1; a <= lines; a++) {
            for(b=1; b<= a; b++) {
                printf("*");
            }
            printf("\n");
        }
}while(1);
system("pause");
}

如果要在用户输入有效值(我的意思是1-15)时停止程序,则将这些for循环放入else块中并添加break语句.

If you want to stop program if user enter a Valid value(I mean 1-15) then put these for loops in else block and add break statement.

do{
    printf("Input a value from 1 to 15: ");
    scanf("%d", &lines);

    //Check if inputed value is valid
    if(lines < 1 || lines > 15) {
        printf("Error: Please Enter a Valid number!!!\n");
        continue;
    }
    else{
    /*create triangle based on inputed value */
        for(a = 1; a <= lines; a++) {
            for(b=1; b<= a; b++) {
                printf("*");
            }
            printf("\n");
        }
        break;
   }
}while(1);
system("pause");
}

这篇关于做到这一点,以便在输入无效值时,用户必须在C中重试新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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