break from while statement

69 views Asked by At

how can i break from my while statement when i want to scanf numbers like 1 2 3 4 5 and then hit Enter and goes on with my code ... here is what i have done but nothing works

while(1){
    res=scanf("%d",&x);
        arr[i++]=x;
        counter++;
            if ( res == 0 ){
                printf("EOF\n");
                break;
            }
            if ( res != 1)
            {
                printf("Nespravny vstup.\n");
                return 1;
            }
            if ( counter > 100)
            {
                printf("Nespravny vstup.\n");
                return 1;
            }
    }
printf("Counter:%d\n", counter);
2

There are 2 answers

2
Siddharth Srinivasan On BEST ANSWER

According to the man page of scanf:

NAME
   scanf,  fscanf, sscanf, vscanf, vsscanf, vfscanf 
...

RETURN VALUE
   These functions return the number of input items  successfully  matched
   and assigned, which can be fewer than provided for, or even zero in the
   event of an early matching failure.

   The value EOF is returned if the end of input is reached before  either
   the  first  successful conversion or a matching failure occurs.  EOF is
   also returned if a read error occurs, in which case the error indicator
   for  the  stream  (see ferror(3)) is set, and errno is set indicate the
   error.

In your case, scanf will return 0 only in case of an early matching failure.

0
Fulgen On

return breaks off the whole function, try break; instead of return.