0

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;
            
         }
     }
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
deafninja
  • 23
  • 2
  • Three possible answers: (1) don't bother trying to fix this; (2) flush the offending input somehow; (3) read full lines of text using `fgets`, then parse (perhaps using `sscanf`). For further info on these, see (1) [this answer](https://stackoverflow.com/questions/2979209/using-fflushstdin/58884121#58884121); (2) [this question](https://stackoverflow.com/questions/7898215); (3) [this question](https://stackoverflow.com/questions/58403537). – Steve Summit Oct 24 '21 at 14:01
  • [Relevant](http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html). – n. m. could be an AI Oct 24 '21 at 14:03

1 Answers1

3

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 
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335