2016-12-22 5 views
0

Как я могу выйти из моей инструкции while, когда я хочу отсканировать цифры, например 1 2 3 4 5, а затем нажать Enter и продолжить с моим кодом ... вот что я сделал, но ничего не работаетbreak from while statement

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); 

ответ

1

Согласно man странице зсапЕ:

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. 

В вашем случае scanf вернет 0 только в случае выхода из строя раннего соответствия.

+0

Да, но как это сделать, если пользователь нажал 1 2 3 и введите код и продолжайте? – blackroad

+0

Чтобы разбить, введите нечисловые символы (например, 'abcd') & Enter или просто' Ctrl + D' –

1

возвращение обрывает всю функцию, попробуйте break; вместо возврата.