se omite scanf

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 exits 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;
}

preguntado el 28 de agosto de 11 a las 01:08

Reason for downvote please ?? -

No puedo entender la pregunta.

Por una cosa, fflush(stdin); is invalid; it invokes undefined behavior. Who taught you to do that? -

The posted code should really be self-contained and complete so people can just run it and see what's happening. -

You're typing in "5 6<return>" and then your program is terminating? Your scanf() call will only read in the first non-whitespace value, which is 5, so then it would terminate. You'd have "enter ur choice" as the last output because you don't have anything for the i == 5 case. -

1 Respuestas

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.

Además, inicializa i antes del bucle.

Respondido 28 ago 11, 05:08

RESPECT !!! after first few comments I was feeling I was doing something dumb .. thanks I wouldnt be able to figure that out - koool

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.