0

fgets() and gets() works properly for the first time. When I use this function for the second time then I am not asked for the input.

#include<stdio.h>
int main(){
    char name[10];
    printf("\nEnter your name: ");//Enter Ram Singh Gupti
    fgets(name,10,stdin);
    printf("\nName using fgets: ");
    puts(name);
    fflushh(stdin);//what to use instead of fflush since it does not supports in linux
    printf("\nEnter your name: ");
    gets(name);
    printf("\nName using gets: ");
    puts(name);
    return 0;
}

Input & Output:

Output Screen My statement gets(name) is not taking input. I think it is taking input from the buffer. How can we resolve this issue. what should I do before gets(name) to clear the buffer.

user3243634
  • 114
  • 2
  • 11
  • Please give the exact expected result vs actual result. – kaylum Mar 24 '21 at 06:25
  • `fgets()` will read the first 9 characters, then `gets()` will read the rest. – Barmar Mar 24 '21 at 06:26
  • You also should stop using `gets()`. It's dangerous because you can't specify the buffer size. It has been removed from the language. – Barmar Mar 24 '21 at 06:29
  • @kaylum fgets() function should only store 9 characters in the 1D char array name whereas gets() function should store the whole name Ram Singh Gupti. – user3243634 Mar 24 '21 at 15:40
  • @Barmar In this example I am just trying to compare fgets() and gets(). Since, gets() is not appropriate to use so I want to see how fgets() works. I want the function gets(name) to take string input and store it in the 1D character array name whereas it is storing the value Gupti from the buffer which fgets() couldnot store. fgets() could store only 9 characters in the 1D name array. – user3243634 Mar 24 '21 at 15:47
  • 2
    You would see the same thing if you called `fgets()` twice. – Barmar Mar 24 '21 at 15:50
  • what should I use instead of `fflush(stdin)` to clear my buffer before taking input using `gets()` function – user3243634 Mar 25 '21 at 06:09

0 Answers0