0

Code 1:-

int main()
{
    char str[200];
    fgets(str,200,stdin);
    printf("%s",str);
    return 0;
}

Output:-

ab cd
ab cd
(line feed)

Code 2:-

int main()
{
    char str[200];
    gets(str);
    printf("%s",str);
    return 0;
}

Output:-

ab cd
ab cd

When I enter ab(space)cd(enter key) , then in case of fgets() I am getting a line feed in the output, whereas in case of gets(), no new line feed is displayed.
What is the matter of the line feed in this case.

kevin gomes
  • 1,775
  • 5
  • 22
  • 30

1 Answers1

1

gets() and fgets() read for a FILE in to the buffer provided until a new-line is detected. The former stores a NUL instead of the new-line, the latter places the NUL after the new-line.

Please note that gets() is unsafe, as it does not provide any way to protect writing beyond the limits of the buffer passed.

fgets() takes the size of the buffer, and stops reading if this size is reached. In this latter case reading might stop before any new-line had been read.

For a general method of chopping of the various kinds of new-lines at the end of a buffer you might like to take a look at this answer: https://stackoverflow.com/a/16000784/694576

Community
  • 1
  • 1
alk
  • 69,737
  • 10
  • 105
  • 255
  • I heard that `gets` is disastrous to use, but in this case `fgets` is disastrous, then is there any alternative of `gets` and `fgets` – kevin gomes Mar 02 '14 at 08:33
  • I am asking for the alternative, because in my case I do not need newline before nul – kevin gomes Mar 02 '14 at 08:36
  • @kevingomes: Please see my even more updated answer. – alk Mar 02 '14 at 08:37
  • one more thing I want to know that why in case of `fgets` I am getting only one `line-feed` in output, there should be two line-feeds , one for input and other for output – kevin gomes Mar 02 '14 at 08:38
  • @kevingomes: You enter **one**, you get **one**. In fact its two, as the prompt is **two** new-lines below the last `d`. **One** following the `d`, and **one** producing the empty line, that is **before** the command-line prompt. – alk Mar 02 '14 at 08:39
  • I didn't get you last explanation – kevin gomes Mar 02 '14 at 08:44
  • `one following d` means – kevin gomes Mar 02 '14 at 08:45
  • There is one new-line after `ab cd`. And one more following the latter, producing the empty line. – alk Mar 02 '14 at 08:47
  • new line should be below `d`, how can it be after `d` – kevin gomes Mar 02 '14 at 08:48
  • 1
    The new-line character is invisible, you just notice it by the cursor being put on a new line. Everthing after the new-line character is written on a new line. – alk Mar 02 '14 at 08:48