0

I have coded the following codes,but there was a problem

char p[20];
int n;
errno = 0;
n = scanf("%[^\n]",p);
if (1 == n)
{
    printf("%s\n",p);
    scanf("%[^\n]",p);  /*no waiting for input*/
    printf("%s\n",p);
}
Fionser
  • 161
  • 2
  • 8
  • 1
    Check out this link: http://stackoverflow.com/questions/6083045/scanf-n-skips-the-2nd-input-but-n-does-not-why – Spot Apr 24 '12 at 15:45

1 Answers1

3
n = scanf("%[^\n]",p);

This says scan every character except \n ie ENTER key. So it allows you to enter a string and you would have pressed ENTER. This ENTER character is still in stdin buffer which will terminate your next scanf statement

scanf("%[^\n]",p);/*no executed*/

and hence it seems to you that it dint execute! scanf, reads first from the buffer, if it doesn't find sufficient data there, then waits for your input.

Feed the ENTER you entered first to some function like getchar(). ie add a getchar() before your second scanf and now your second scanf will accept input from stdin

Something like

if (1 == n)
{
    printf("%s %d\n",p,n);
    getchar();
    scanf("%[^\n]",p);/*no executed*/
    printf("%s\n",p);
}
Pavan Manjunath
  • 27,404
  • 12
  • 99
  • 125