make it so when an invalid value is inputted the u

2019-02-28 09:43发布

问题:

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

回答1:

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


回答2:

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


标签: c input