-1
#include<stdio.h>
int main()
{
   char str[100];
   printf("Enter a string: ");
   fgets(str, sizeof(str), stdin);
   fputs("Liverpool", stdout);
   fputs("Manchester", stdout);
   return 0;
}

OUTPUT

Enter a string : punch
LiverpoolManchester

But, when I am taking the input from the user, it is not giving the expected output.

#include<stdio.h>
int main()
{
   char str[100];
   printf("Enter a string: ");
   fgets(str, sizeof(str), stdin);
   fputs(str, stdout);
   fputs(str, stdout);
   return 0;
}

OUTPUT

Enter a string : punch
punch
punch

The only change between the two codes is, I was specifying the string in the previous one and in the latter, I am taking the input from the user. Can anybody tell me the reason behind this ??

Got_R3kt
  • 1
  • 3
  • 2
    "it is not giving the expected output". What do you expect the output to be? – kaylum Apr 30 '20 at 06:15
  • 1
    The difference in the output clearly implies that the string in the second example contains a newline character. It has to. And sure enough, if you look at the man page for `fgets`, it *says* that it includes the newline character. Try to read the man page for a function more carefully. It describes exactly how `fgets` works. – Tom Karzes Apr 30 '20 at 06:17

2 Answers2

2

The fgets function reads up until and including the newline.

So the buffer you pass to fputs will include the newline from the fgets call, which of course will be adding new lines in the output.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Check out these two links on the functions fgets and fputs.

http://www.cplusplus.com/reference/cstdio/fgets/ http://www.cplusplus.com/reference/cstdio/fputs/

It will help you more to read those yourself definitely. But it seems that when using fputs it doesn't automatically append a newline character \n at the end of your string.

In your first example by specifying the specific string hard coded the newline isn't added. When you use fgets it WILL automatically append a \n at the end. So when you output str instead of "Liverpool" or "Manchester" it's storing "punch\n" not just "punch".

Nick
  • 151
  • 1
  • 1
  • 6