当输入无效值时,用户必须重试C中的新值

当输入无效值时,用户必须重试C中的新值,c,input,C,Input,对于我的硬件分配,我必须创建一个程序,根据用户输入输出一个基于星号的三角形。我已经让我的程序在用户输入一个整数时工作,输出正确的三角形,但我的问题是当输入一个无效值时,我如何使它工作,以便用户必须重新尝试提交一个值?我查看了论坛,没有找到类似的问题 #include <stdio.h> int main() { int lines, a, b; //prompt user to input integer printf("Input a value from 1 to 15: "

对于我的硬件分配,我必须创建一个程序,根据用户输入输出一个基于星号的三角形。我已经让我的程序在用户输入一个整数时工作,输出正确的三角形,但我的问题是当输入一个无效值时,我如何使它工作,以便用户必须重新尝试提交一个值?我查看了论坛,没有找到类似的问题

#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");
}
你可以用doo。。while循环向用户请求有效输入。代码

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

    do {

        //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");
           }

           break; //break while loop after valid input
        }
       else {
          printf("not valid");/* repeat code in this else statement, maybe */
       }
   }while(1);
   system("pause");
}
若你们想停止程序,若用户输入了一个有效值,我的意思是1-15,那个么把这些for循环放到else块中,并添加break语句

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");
}

请给出一个无效值的示例。例如20,0x5,1000,abc。。。
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");
}