0

How can I handle stray characters input as shown in below code snippet

#include <stdio.h>


int main ()
{
    int i, j=0;
    while (j <3)
    {
        printf("\n Enter the number to be displayed ");
        scanf("%d",&i);
        printf("\n The number to be displayed is %d \n", i);
        j++;
    }
    return 0;
}

Output

philipa@hq1-up-swe-01{1436}: ./a.out
 Enter the number to be displayed 45/
 The number to be displayed is 45
 Enter the number to be displayed
 The number to be displayed is 45
 Enter the number to be displayed
 The number to be displayed is 45

Here '/' is added mistakenly. I want to flush this '/' before it taken as input for next loop. How can I handle this situation?

1 Answers1

2

You can use the one single loop,

int c;
while((c=getchar()) != '\n' && c != EOF);

It will clear the input buffer. Place this after the scanf.

while(1)
{ 
   switch(opt)
   {
    ...
    ...
    ...
   }
   while((c=getchar()) != '\n' && c != EOF); // It will clear the buffer before getting the next value.
}
Karthikeyan.R.S
  • 3,991
  • 1
  • 19
  • 31
  • I have added the loop on purpose to highlight the issue. I want to know if there's any way to handle this exception. Say while performing operation on Linked list while (1) { printf("\n 1.Insert Operation "); printf("\n 2.Display Operation "); . . . printf("\n 10.Exit"); printf("\n Enter the operation to be performed on the linklist\n"); scanf("%d", &i); if (i < 0 || i > 10 || i != 0-9) { printf("\n INVALID INPUT !!!!!!!!!!!!!!!\n "); continue ; } – Austin Philip D Silva Feb 17 '15 at 10:02
  • You have to do that in the while loop? – Karthikeyan.R.S Feb 17 '15 at 10:03
  • 4
    `c` should be an `int` , not a `char`. – Spikatrix Feb 17 '15 at 10:07
  • @Karthikeyan.R.S Can you please explain why '/' is causing problem both the times in the loop.? – Austin Philip D Silva Feb 17 '15 at 10:17
  • You are getting the input using the scanf mentioning to get the integer. '/' is character so it does not read by the scanf . So it remains in the buffer. every time scanf get the value it will come. So the scanf every time fails. It take the first value given correctly, otherwise garbage value. – Karthikeyan.R.S Feb 17 '15 at 10:20