0
#include <stdio.h>

int main()
{
    int mynumber;
    while(1){
        scanf("%d",&mynumber);
        if(mynumber>0){
            while(mynumber>0){
                printf("%d ",mynumber--);
            }
            printf("\n");
        }else{
            return 0;
        }
    }
}

If user inputs an int, it works as intended. When float is given it prints all numbers but exits loop at the same time.

I want to learn why and how this could happen?

zuxi
  • 3
  • 3
  • 3
    I recommend you check what [`scanf`](http://en.cppreference.com/w/c/io/fscanf) *returns*. – Some programmer dude Sep 08 '17 at 09:41
  • Since `.` is not accepted, `return 0;` is executed in the next loop. – BLUEPIXY Sep 08 '17 at 09:42
  • 1
    As for your problem, when `scanf` sees the decimal-point (or comma) in the input, it will stop parsing the input, since that character can't possibly be part of a decimal integer number. *However*, that decimal-point will be left in the input buffer for the next call to `scanf`. Which will see the decimal-point, fail, and leave it in the buffer. And so on and on... – Some programmer dude Sep 08 '17 at 09:43
  • Using `scanf` for user input is evil. Use `fgets` and do the parsing yourself. – Jabberwocky Sep 08 '17 at 09:43
  • @Someprogrammerdude; Your second comment is the answer I was about to write. – haccks Sep 08 '17 at 09:43
  • By the way, if `scanf` fails it will not modify the argument. That means if `scanf` fails, then `mynumber` is still uninitialized and will have an *indeterminate* (and seemingly random) value. Another reason to check what `scanf` returns. – Some programmer dude Sep 08 '17 at 09:46
  • @MichaelWalz; It's evil only when you want string as input. – haccks Sep 08 '17 at 09:46
  • @Someprogrammerdude thank you. i got it. i think i also check/see/read how scanf works. edit: I think comments are not flagged as answer. thank you again. – zuxi Sep 08 '17 at 09:47

0 Answers0