0

For example:When i tried running the following program, it just skipped the reading of str. Please explain the reason to this , and also which is right the way to do it?

#include<stdio.h>
#include<string.h>
void main()
{
    char str[50];
    int m;
    scanf("%d",&m);
    gets(str);
    printf("\n%d",strlen(str));
}
  • 1
    After scanf the new line (\n) from hitting the enter is still in the input buffer and gets reads that, it reads until it not finding a new line, it find it immediately so making an empty string. You can do this `"%d%*c"` to "eat" that new line char also. – Eraklon Apr 02 '20 at 14:57
  • If you open stdin once(scanf), you won't be able to do it again(gets), you'll need some more convenient way to read stdin. – BladeMight Apr 02 '20 at 14:58
  • 1
    [Never use `gets()`](https://stackoverflow.com/q/1694036/1679849) – r3mainer Apr 02 '20 at 15:01
  • Try not to mix your input methods, and as commented, `gets` is no longer part of C. – Weather Vane Apr 02 '20 at 15:04
  • @WeatherVane good catch on that dupe. – Marco Bonelli Apr 02 '20 at 15:06

0 Answers0