-3

Trying to make a C program that takes eg. 5 user inputs in a float array. Then prints the array and prints another array that accumulates the numbers. It works fine but how do i break the input and print "not a number" if the input is non-nummerical?

#include <stdio.h>

int main(){
    float i,sum;
    sum=0;


    const int ARRAYSIZE = 5;


    float array1[ARRAYSIZE];

     printf("Input a number (a total of %d numbers is needed):\n", ARRAYSIZE);
     fflush(stdout);

     for(int i = 0; i < ARRAYSIZE;  i++){
        scanf("%f", &array1[i] );
     }

    for(int i = 0; i < ARRAYSIZE; i++){
        printf("You typed in: %.2lf\n",array1[i]);

        }

    for(int i = 0; i < ARRAYSIZE; i++){

        sum+=array1[i];
        printf("The accumulated value if the input is: %.2lf\n", sum);
    }

    return 0;
}
deafninja
  • 23
  • 2
  • CHECK SCANF'S RETURN VALUE!!! (Sorry to shout, but this is a little-known, very good thing to do anyway, the more so when the question involves "stopping on non-numeric input".) – Steve Summit Oct 11 '21 at 18:48
  • The only (potential) complication is that if you want to take additional input from the user, after the numeric input and the non-numeric input that terminates it, you are going to have to flush the non-numeric input somehow (ideally via some way *other* than the dreaded `fflush(stdin)`). – Steve Summit Oct 11 '21 at 18:52

1 Answers1

1

Check the return value of scanf

 if(scanf("%f", &array1[i] ) != 1)
 {
     printf("Invalid number\n");
     /* so more code */
 }
0___________
  • 60,014
  • 4
  • 34
  • 74
  • Thx for the answer. If i change it to the code below how do i stop the last 2 "for loops" from not continuing to write 5 non valid lines per loop? ` for(int i = 0; i < ARRAYSIZE; i++){ if(scanf("%f", &array1[i] ) != 1) break; { printf("Invalid number\n"); /* so more code */` – deafninja Oct 11 '21 at 19:15
  • 1
    @deafninja After the first (input) loop, say `int nelements = i;`. That's the number of elements the loop actually read, which might be less than `ARRAYSIZE`. Then, make the second and third loops go up to `nelements` instead of `ARRAYSIZE`. – Steve Summit Oct 11 '21 at 19:50