c - How to end an input when enter is passed -


#include <stdio.h> #include <string.h> int main() {     int array[1000]={0}, n, c, d, swap;     printf("enter number of elements\n");     scanf("%d", &n);      printf("enter %d integers\n", n);      (c = 0; c<n; c++)         scanf("%d", &array[c]);       (c = 0 ; c < ( n - 1 ); c++)     {         (d = 0 ; d < n - c - 1; d++)         {             if (array[d] > array[d+1]) /* decreasing order use < */             {                 swap       = array[d];                 array[d]   = array[d+1];                 array[d+1] = swap;             }         }     }      printf("sorted list in ascending order:\n");      ( c = 0 ; c < n ; c++ )         printf("%d\n", array[c]);      int result= array[n-1]-array[0];     printf("the difference between largest , smallest: %d",result);     puts("");     return 0; } 

this program bubble sorts inputs first , gives output of difference between largest , smallest number. want end input when type enter. example, input = 6 4 2 , output= 4. (end input 'enter')

to end input when enter or '\n' occurs challenging using scanf("%d",... "%d" first consumes white-space including '\n'. need different way watch '\n' first.

for (c = 0; c<n; c++)   int ch;   while ((ch = fgetc(stdin)) != '\n' && isspace(ch));   if (ch == '\n' || ch == eof) break;   ungetc(ch, stdin);   if (scanf("%d", &array[c]) != 1) handle_nonnumericinput(); } 

or better yet, use fgets(). easy catch sorts of invalid input.

#include <limits.h> #define max_int_size (sizeof(int)*char_bit/3 + 3)  c = 0; char buf[n*(max_int_size + 1) + 2]; if (fgets(buf, sizeof buf, stdin)) {   char *p = buf;   (; c<n; c++)     int n;     if (sscanf(p, "%d %n", &array[c], &n) != 1) break;     p += n;   }   if (*p) handle_missing_or_extra_or_nonnumeric_input();  } 

Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -