make it so when an invalid value is inputted the u

2019-02-28 09:56发布

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

标签: c input
2条回答
做自己的国王
2楼-- · 2019-02-28 10:44
#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");
}

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");
}
查看更多
我只想做你的唯一
3楼-- · 2019-02-28 10:45

You can use do .. while loop to ask user for valid input. Code

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");
}
查看更多
登录 后发表回答