-1

I created a program to let user input the number there credentials . Before that they have to declare the number of employees present . Whenever i run the code and enter the value of variable people ; after that instead of asking for an input it gives of Name == name is as an output Is there any explanation for it

#include<stdio.h>

struct employee{
char name[40];
char company[40];
int age;
};

int main(){

    int people;
    printf("How many peoplees data is being entered : ");
    scanf("%d",&people);

    struct employee credentials[people];

    for(int count=0;count<people;count++){
        printf("Name == ");
        gets(credentials[count].name);

        printf("name is %s\n\n",credentials[count].name);
    }

return 0;
}
  • 1
    First of all never ***ever*** use the `gets` function! It's [so dangerous](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) that it was marked as obsolete in the mid 1990's, and removed from the C language altogether in the C11 specification, ten years ago. Use e.g. [`fgets`](https://en.cppreference.com/w/c/io/fgets) instead. – Some programmer dude Nov 26 '21 at 11:52
  • As for your problem, think about what happens with the `Enter` key that you most likely pressed after the input for `people`... It's added into the input buffer as a *newline* `'\n'`. Which will bet the first character `fgets` (or the bad `gets` in your case) reads. – Some programmer dude Nov 26 '21 at 11:53
  • The dangers of `gets()` are described [in this stackoverflow post](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – mmixLinus Nov 26 '21 at 12:35
  • Does this answer your question? [fgets doesn't work after scanf](https://stackoverflow.com/questions/5918079/fgets-doesnt-work-after-scanf) (Note also, the parent duplicate: [scanf() leaves the new line char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer)). – Oka Nov 26 '21 at 12:56

1 Answers1

0

Your scanf has left \n in the buffer. This character is being read and consequently printed. Change the format and it should work "%d "

int main(){

    int people;
    printf("How many peoplees data is being entered : ");
    scanf("%d ",&people);

    struct employee credentials[people];

    for(int count=0;count<people;count++){
        printf("Name == ");
        fgets(credentials[count].name, sizeof(credentials[count].name) - 1, stdin);

        printf("name is %s\n\n",credentials[count].name);
    }

    return 0;
}

https://godbolt.org/z/q1dYxd9q1

0___________
  • 60,014
  • 4
  • 34
  • 74