0

I am trying to match the input of a string by user with that of the string from a file. But there are two things that is not happening the right way.

typedef struct
{
    int yyyy;
    int mm;
    int dd;
} Date;

int main()
{
    FILE *fp2;
    fp2=fopen("StudentId.txt","r");

    char input[255];
    char *id;
    id = (char *)malloc(sizeof(Date));

    printf("Enter your UserId:\n");
    gets(id);
    gets(id);
    fgets(input,sizeof(input),fp2);
    int cmp;
    printf("%s_\n%s_\n",input,id );
    return 0;
}

Firstly I have to use two gets(id) instead of one as the program seems to skip the first one. Second, the after getting stored is printed as follows

Aditya828
_Aditya828_

Which makes me wonder why is it storing input with a '\n' and id not. Is there any way to fix the issues?

  • First of all never ever use `gets`. It's a [*dangerous*](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) function that has even been removed from the C standard. Secondly, `d = (char *)malloc(sizeof(Date));`? That makes no sense. `Date` is a structure of integers, `id` is a a pointer to `char` (which together with your use of it indicates it's a string). Those two are different things. Thirdly, you do `gets(id)` directly followed by `gets(id)`. What do you think will happen with that? – Some programmer dude Jun 09 '20 at 17:31
  • @Someprogrammerdude i have to use ```gets(id)``` twice because because the first one is skipped abruptly. –  Jun 09 '20 at 18:15

1 Answers1

1

why is it storing input with a '\0' and id not.

This conclusion misinterprets the results.

Both id and input have a string terminating null chracter '\0'.
input also has '\n' as fgets() retains the line-feed. gets() does not.

Is there any way to fix the issues?

Avoid gets(). It is bad.

Instead use fgets() to read id.

Use a buffer sized based on the text represeatation of id, not the size of Date. Be generous.

#define ID_MAX_SIZE 40    // Expected max size
char id[ID_MAX_SIZE * 2]; // Be generous.  Later code can trucate if needed.

if (fgets(id, sizeof id, stdin)) {
  id[strcspn(id, "\n")] = '\0'; // Lop off potential \n
  printf("id: <%s>\n", id);
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256