0

Hear me out because I'm a noob and I know this is a potential duplicate but I've browsed so much pages and I still can't figure this out. I'm trying to take a name but for some reason it's not allowing me to input data into first fgets.

void getModuleDetails(struct moduleInfo* moduleInfo)
{

    FILE *fp;
    fp = fopen("moduleInfo.txt", "a+");
    if(fp == NULL)
        exit(1);

    char name[100];
    char code[100];
    int id;
    int ca;
    int exam;

    while((ch =getchar())!= '\n' && ch != EOF)
    {
        printf("Module Name:");
        if(fgets(name, 100, stdin) != NULL)
        {
            fprintf(fp,"%s", name);
        }
    }

    printf("Module Code:");
    if(fgets(code, 100, stdin) != NULL)
        fprintf(fp,"%s", code);

    printf("Module ID:");
    if(scanf("%d", &id) != NULL)
        fprintf(fp,"%d\n", id);

    printf("CA%:");
    if(scanf("%d", &ca) != NULL)
        fprintf(fp,"%d\n", ca);

    printf("Exam%:");
    if(scanf("%d", &exam) != NULL)
        fprintf(fp,"%d\n", exam);

    fclose(fp);
}

As you can see I have removed all '\n's that I had after my printf's, added getchar to handle a \n. I also know I shouldn't be mixing fgets with scanf but it's what our lecturer wants. If anyone could point out where I'm going wrong, it'd be extremely appreciated.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
Raddish18
  • 31
  • 4
  • That's not an answer to your question, but please don't compare `scanf()` return value with `NULL`. Please read `man scanf` to find that it's return value is `int` and not a pointer. –  Oct 21 '17 at 02:10
  • 1
    What do you think is happening when you call `fgets` **inside a loop** that is calling `getchar()`? (additionally, you generally pass a `FILE*` parameter to avoid hardcoding the filename within the function) – David C. Rankin Oct 21 '17 at 02:14
  • @BronislavElizavetin Thanks for the advice, didn't even think of looking at the man. – Raddish18 Oct 21 '17 at 14:19
  • @DavidC.Rankin Yeah I removed that getchar while loop and actually just put getchar(); in my switch condition before I call the method. Much noob here, I was just following something I saw on a similar question. – Raddish18 Oct 21 '17 at 14:22
  • You will get there. There is a lot to learn in C, and learning it isn't a race, it's more of a journey. Best advise anyone can give on learning C is to *slow down*... Absorb the details. You are working at the hardware level and you are completely responsible for accounting for each byte, whether in memory allocation or when reading/writing to a file stream. To a large degree that is why C is so wicked fast. There is no overhead trying to hide the details of programming from you. It is also why is takes a bit longer to become comfortable with C. Don't worry, you will get there. – David C. Rankin Oct 21 '17 at 14:37
  • Thank you @DavidC.Rankin! Great advice! – Raddish18 Oct 21 '17 at 16:46

0 Answers0