scanf is skipped
I have the following code and I have defined the functions that I am calling here, the problem here is : I run the code input: 1 input: 2 input: 2 input: 6 input: 5 6 // for the scanf associated with i=6; after this I get the output on the screen as enter ur choice and then it exit开发者_开发知识库s out of the program ... its like the scanf gets the value from somewhere but I dunno from where I also tried fflush(stdin) doesnt seem to work can any one please help
int main()
{
int i,*j,k,pos,val;
Element *stacka = new Element;
stacka =NULL;
while(i!=5)
{
printf("Enter ur choice \n");
fflush(stdin);
scanf("%d",&i);
if(i==1)
{
if(createStack(&stacka))
{
printf("yes");
}
}
if(i==2)
{
k=2;
if(push(&stacka,&j))
{
printf("yes");
}
}
if(i==3)
{
if(pop(&stacka,&k))
{
printf("yes %d",k);
}
}
if(i==4)
{
if(emptyStack(&stacka))
{
printf("yes");
}
}
if(i==6)
{
scanf("%d,%d",&pos,&val);
fflush(stdin);
insert_at_pos(pos,val,&stacka);
}
}
return 0;
}
Try inserting a space before %d
:
scanf(" %d,%d",&pos,&val);
This will eat any leading whitespace that might be in the input buffer, e.g., the newline from the earlier entry of i
.
Also, initialize i
before the loop.
精彩评论