Search code examples
cfor-loopif-statementdoublescanf

In C programming - How to get new scanf input after this if statement breaks the loop


This is the first part of my code. An array of 5 numbers are entered. Then it writes them out and accumulates them.

I want to reenter the loop with the goto TAG if a number is not entered. Problem is when the for loop is interrupted by a non numerical value and writes "That is not a number" im not asked to input another value - it just goes into an endless loop.

How do i fix this?


int main(){
    double i;

    const int ARRAYSIZE = 5;

    double array1[ARRAYSIZE];
    double array2[ARRAYSIZE];

    TAG:
     printf("Input a total of %d. numbers.\n", ARRAYSIZE);
     printf("The numbers will be accumulated:\n");
     fflush(stdout);


     for(int i = 0; i < ARRAYSIZE;  i++){
         if(scanf("%lf", &array1[i]) != 1)

         {
             printf("That is not a number - try again\n");
             goto TAG;
            
         }
     }

Solution

  • For starters this variable and this array

    double i;
    
    double array2[ARRAYSIZE];
    

    are not used in the program.

    Using the goto statement is a bad programming practice.

    Your code can be rewritten for example the following way

    #include <stdio.h>
    
    int main(void) 
    {
        enum { ARRAYSIZE = 5 };
    
        double array1[ARRAYSIZE];
        
        printf( "Input a total of %d. numbers.\n", ARRAYSIZE );
        puts( "The numbers will be accumulated:" );
         
        for ( int i = 0; i < ARRAYSIZE; i++ )
        {
            int success;
            
            while ( ( success = scanf( "%lf", array1 + i ) ) != 1 )
            {
                printf("That is not a number - try again\n");
                scanf( "%*[^\n]%*c" );
            }
        }
         
        for ( int i = 0; i < ARRAYSIZE; i++ )
        {
            printf( "%f ", array1[i] );
        }
        
        putchar( '\n' );
        
        return 0;
    }
    

    The program output might look like

    Input a total of 5. numbers.
    The numbers will be accumulated:
    1
    A
    That is not a number - try again
    2
    B
    That is not a number - try again
    3
    C
    That is not a number - try again
    4
    D
    That is not a number - try again
    5
    1.000000 2.000000 3.000000 4.000000 5.000000