Advertisement
Lisaveta777

get rid of rest input getchar &scanf

Aug 22nd, 2018
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.78 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <ctype.h>
  3. //most important here is how to get rid of unwanted input in scanf and getchar, lines 23-26, 56-57
  4. int main(void)
  5. {
  6.     char ch;
  7.     int n,m;
  8.     int sc_res,flag,count;
  9.     printf("1) +, 2) -, 3) *, 4) /,  Q for quit\n");
  10.  
  11.     while((ch=getchar())!='Q')
  12.     {
  13.         if(ch>'4'||ch<'1')
  14.         {
  15.             printf("wrong input, try again\n");
  16.         }
  17.         else
  18.         {
  19.             flag  = 1;     //*****
  20.             count = 0;
  21.             while(scanf("%d %d",&n,&m)!=2)
  22.             {
  23.                 //scanf("%*[^\n]");//next 3 lines equals? and gets rid of bufer?threat?, so that next time scanf
  24.                                    //can take new input
  25.                 //fflush(stdin);
  26.                 rewind(stdin);
  27.                 printf("Error Input 2 numbers again\n");
  28.  
  29.             }
  30.  
  31.             switch(ch)
  32.             {
  33.             case '1':
  34.                 printf("%d plus %d is %d\n",n,m,n+m);
  35.                 break;
  36.             case '2':
  37.                 printf("%d minus %d is %d\n",n,m,n-m);
  38.                 break;
  39.             case '3':
  40.                 printf("%d multiplied by %d is %d\n",n,m,n*m);
  41.                 break;
  42.             case '4':
  43.                 {
  44.                     while(!m)  //if user input 0 as divider  ***
  45.                     {
  46.                         printf("enter non-zero value\n");
  47.                         scanf("%d",&m);
  48.                     }
  49.                     printf("%d divided by %d is %d\n",n,m,n/m);
  50.  
  51.                 }
  52.             }//end of switch
  53.         }//end of big else
  54.         printf("1) +, 2) -, 3) *, 4) /,  Q for quit\n");
  55.  
  56.         while(getchar()!='\n')//getting rid of the rest of input,including newline ***
  57.             continue;
  58.     }
  59.  
  60.     return 0;
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement