2

I am creating a function to read in inputs from the user and put them into a floating point array of numbers with predetermined fix size of 25. It also returns the total amount of items that the user enters. However, for some reason this code will not terminate when I enter 999. I know it is something to do with that it is an int and input is a float, but I don't really know how to fix this (only been learning C for five days).

int readArray(float a[]){
    //accepts inputs and puts items in a predefined array of size 25    
    int index = 0;
    float input;
    printf("Enter 25 or less elements for array (999 to finish):\n");

    scanf("%d", &input);  //accept initial response; priming prompt
    printf("1st Prompt accepted");

    while (input != 999 && index < 25) {
        printf("In while loop");

        a[index] = input;
        index++;
        scanf("%d", &input);
    }
    return (index);

}
2
  • Oh just realized, the two prints: printf("1st Prompt accepted"); and printf("In while loop"); are just debug code. Commented Apr 28, 2013 at 2:58
  • possible duplicate of Reading floats into an array Commented Apr 28, 2013 at 3:41

1 Answer 1

6

The proper format specifier matters a lot here.For float it is %f.So change your scanf() to

scanf("%f", &input);
Sign up to request clarification or add additional context in comments.

2 Comments

To the downvoter, I dare you to accept float numbers in C using %d format specifier for scanf().Tell me how on earth it's possible to use %d for floats and I'll give up C and go to Afghanistan and grow poppy there.
@NikBougalis Please confirm that 999 is promoted to float before the comparison in input!=999 and that's why there is no issue with the expression and the program works fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.