Search code examples
cinfinite-loopdo-while

Infinite do-while loop on C (2 conditions)


In this part of my program in C the Do-While goes infinite. i was trying to make a
loop for the case that someone wanted to type a string instead of numeric value.

int main(){
    int cnotas;

    do{
    printf("\nIngrese la Cantidad de Notas del Estudiante\n--------------------------------------------\n");    //asks for the number of grades that are going to be used in the average calculation

    if(cnotas>=1){    //if statement to break the loop when the amount of grades is 1 or more
        break;
    }

    }while(scanf("%d", &cnotas)==0 && cnotas<1);    \\gets the cnotas value and checks if is valid
    promedioe(cnotas);
    system("pause");
}

Updated!

Forget to mention that i want to reject non numeric inputs from the user, so the program doesn't crash.


Solution

    • In this statement: while(scanf("%d", &cnotas)==0 && cnotas<1); you are expecting no input to be entered by the user since scanf returns the no. of inputs successfully read. At the At the same time you are expecting the input value to be lesser than 1.

    • cnotas is auto variable so its starting value may be anything, initialize it.

    • Better make it: }while(scanf(" %d",&cnotas)==1 && cnotas<1);

    • Apart from all this you have written comments with wrong tag \\ rather than //.