Belphegor
Belphegor

Reputation: 1843

Why is my while loop acting this way?

I am currently trying to get a while loop working, but it's not going the way I want it too. What I want to do is loop until a specific input is put in. Something must be wrong with my syntax, but I can't figure out what.

#include <stdio.h>

int main()
{
    float input = 0;
    scanf("%f", &input);
    while(input!=0)
    {
        printf("hello\n");
        scanf("%f", &input);

    }
     return 0;
}

For some reason, it doesn't break out of the while loop when it is zero. I want the while loop to stop working after someone enters 0, but when someone enters 0 it will create an infinite printing of "hello" instead..As you may have guessed, input becomes 0 whenever the user inputs anything besides a float, so if I enter a letter, I am expecting the while loop to stop, but it doesn't ;\

Edit:

Thank you guys for help! I learned and figured out why my logic was wrong (due to lack of understanding how to test the value of scanf)!! Cheers.

Upvotes: 0

Views: 103

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311156

Write the loop like

    while(input!=0)
    {
        printf("hello\n");
        input = 0.0;
        scanf("%f", &input);

    }

Upvotes: 0

nneonneo
nneonneo

Reputation: 179717

input does not become zero if the user enters a non-float. scanf won't change the value, and it won't consume any characters. So, if the user enters a non-float, scanf will keep reading the same characters over and over again.

You can test the scanf return value to see if it successfully read anything. scanf returns the number of fields that were successfully read, so a return value of 0 means that it failed to parse anything:

while(scanf("%f", &input) == 1) {
    printf("You entered %f\n", input);
}

Upvotes: 4

Related Questions