0

This code will work fine if I use fgets() first and then scanf(),but not the other way around. Why?

#include<stdio.h>
#include<string.h>

int main(void) 
{
    int n;
    char a[100];

    scanf("%d",&n);                  //accept a number from user
    fgets(a,100*sizeof(char),stdin); //accept a string from user

    printf("%d\n",2*n);
    printf("%s\n",a);

    return 0;
}
user3078414
  • 1,942
  • 2
  • 16
  • 24
canopus7
  • 1
  • 4
  • 1
    (1) you have to consume the trailing newline from `stdin` buffer before calling `fgets`. (2) You don't need `sizeof(char)` in `fgets`, it equals `1`. Please, have a look at [this SO post](http://stackoverflow.com/questions/14565956/how-to-get-newline-character-from-scanf-even-if-its-the-only-input). – user3078414 Jul 31 '16 at 07:58
  • Add a `getchar()` after `scanf` to consume the newline and you're good. The `sizeof(char)` is ok, it makes the intention clear. – artm Jul 31 '16 at 08:01
  • @artm, thanks for the comment. I didn't mean `sizeof(char)` was wrong, just _extraneous_, because `fgets()` reads characters so and so, which makes the code unnecessarily verbose. – user3078414 Jul 31 '16 at 08:07
  • @user3078414 `fgets(a, sizeof(a), stdin);` is better I suppose.. – artm Jul 31 '16 at 08:09
  • Of course @artm, `sizeof(a)` is the best, because it is most maintainable! (-: – user3078414 Jul 31 '16 at 08:12

0 Answers0