Home > Back-end >  How am I accidentally filtering my input?
How am I accidentally filtering my input?

Time:11-21

        int velikostVstupu=0;
        while(scanf("%d", vstup velikostVstupu)!=EOF){
                velikostVstupu  ;
                if(velikostVstupu>2000){
                        printf( "Nespravny vstup.\n");
                        return 0;
                }
        }

This code is supposed to input no more than 2000 int values into my array "vstup[2000]". But nowhere do I check if the input is int, yet if it isn't, it succeeds my "if(velikostVstupu>2000)" (that's where I check if I am not over 2000).

Why is that? What is the math behind that?

CodePudding user response:

scanf() may fail to read a number and return 0. Unless the input buffer changes it will do so forever till you reach your count limit. Each of arrays will be undefined after that point. You haven't told us how what that input looks like to handle the "skip non-numbers".

You overflow the array when you read entry with vstup == 2000 as the test is after you already read in the value (undefined behavior). This is how I would write it:

#include <stdio.h>
#define MAX_VSTUP 2000

int main(void) {
    int vstup[MAX_VSTUP];
    size_t velikostVstupu=0;
    for(; velikostVstupu < sizeof vstup / sizeof *vstup; velikostVstupu  ) {
        if(scanf("%d", vstup velikostVstupu) != 1)
            break;
    }
    printf("Nespravny vstup %zu.\n", velikostVstupu);
}

and here are some example runs:

$ seq 1 | ./a.out
Nespravny vstup 1.
$ seq 2000 | ./a.out
Nespravny vstup 2000.
$ seq 2001 | ./a.out
Nespravny vstup 2000.

CodePudding user response:

Thanks to @JonathanLeffler i think i know what is happening when inputing non number. it reads only until non number leaving the rest in buffer. When the next one asks it ignores white spaceses and he instantly finds a non number taking nothing and leaving buffer the same but incementing velikostVstupu. And this goes on until velikostVstupu>2000.

  •  Tags:  
  • c
  • Related