SOLUTION OF INFINTE LOOP WHLE SCANNING INVALID DATA TYPE

When you encounter such a problem where user have to input data into program and he gives invalid data type e.g(instead of giving number he gives character) and it causes program to terminate or running infinite time.

e.g
void push()
{
int data;
struct node *q,*temp;

cout<<"Enter elemets: ";
cin>>data;

temp=new node;

temp->info=data;
temp->link=NULL;

if(start==NULL)
 start=temp;
else
{  q=start;
  while(q->link!=NULL)
  q=q->link; 
  
  q->link=temp;

}
}

}

 In above if in this stack if user tries to give char type than it will run infite time.

So to solve this problem.I use    cin.good()to check ....and If user give invalid type it will jumps to
start: after doing it clear  cin.clear()  and ignoring cin.ignore() function.


void push()
{
int data;
struct node *q,*temp;
start:
cout<<"Enter elemets: ";
cin>>data;
if(cin.good()){
temp=new node;

temp->info=data;
temp->link=NULL;

if(start==NULL)
 start=temp;
else
{  q=start;
  while(q->link!=NULL)
  q=q->link; 
  
  q->link=temp;

}
}
else
{ cout<<"Enter valid data \n";
 cin.clear();
 cin.ignore(10, '\n');
 goto start;
 
}
}

0 comments:

Post a Comment

My Instagram