0

I use a

scanf("%d%d",&row,&col); // row & col is int

before

fgets(buf, MAXLEN, stdin); //MAXLEN == 65535 ; buf is char  

I want to input buf after input row and col

but fgets will be skip

May someone help me?

昌翰余
  • 19
  • 3
  • Can you provide an example of the user's input? – Nick Reed Oct 19 '19 at 17:54
  • 2
    Use fgets for both and move on to more important improvements. :) – klutt Oct 19 '19 at 17:54
  • You can use `fgets` in combinatin with `sscanf`. See my answer here: https://stackoverflow.com/a/58403955/6699433 – klutt Oct 19 '19 at 17:55
  • Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). Better not to mix the methods. – Weather Vane Oct 19 '19 at 19:09

1 Answers1

0

This issue can arise if your input is on two separate lines. scanf() will leave a newline character in the buffer; when fgets() tries to read the remainder of the input, it will receive the newline character and stop reading. The following may fix your code:

scanf("%d%d\n", &row, &col);

This will read the newline in as well, leaving the rest for fgets().

Nick Reed
  • 4,989
  • 4
  • 17
  • 37
  • 2
    This will also read ALL whitespace after the second number, and won't return until a non-whitespace character is available on the input (which it will leave there). This may be a problem in an interactive situation, for example if the program wants to print a prompt before the fgets -- it will appear to "hang" (no prompt will print) until a line with a non-whitepace character is entered. At which point it will print the prompt and read the line entered just before the prompt. – Chris Dodd Oct 19 '19 at 18:32