0

here I have a code that uses explicit typecasting to make the initials of the students turn them into the their own ID number. Everything else works fine but the only problem I have encountered is that my code wont read the second full name of user input. It automatically skips over to getting the First names initial again. I've tried with fgets and it works fine but the second time I used fgets it won't work. Newbie here so any help will be appreciated thank you!

#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("     PROGRAM IN C THAT CONVERTS STUDENTS INITIAL TO STUDENT ID     \n");
    printf("==================================================================\n");
    printf("INSTRUCTIONS: Answer in CAPITAL Letters\n\n");

    int num1, num2, num3, num4, num5, num6;
    char Studname1[50];
    char Studname2[50];
    char f1, f2;
    char m1, m2;
    char l1, l2;

    printf("Enter First Student Full Name: ");
    fgets(Studname1, sizeof Studname1, stdin);
    printf("Enter initial of first name: ");
    scanf(" %c", &f1);
    printf("Enter initial of middle name: ");
    scanf(" %c", &m1);
    printf("Enter initial of last name: ");
    scanf(" %c", &l1);

    printf("Enter Second Student Full Name: ");
    fgets(Studname2, sizeof Studname2, stdin); //for some reason the program skips over this
    printf("Enter initial of first name: ");
    scanf(" %c", &f2);
    printf("Enter initial of middle name: ");
    scanf(" %c", &m2);
    printf("Enter initial of last name: ");
    scanf(" %c", &l2);


    num1 = f1;
    num2 = m1;
    num3 = l1;
    num4 = f2;
    num5 = m2;
    num6 = l2;

    printf("\nStudent1 Name: %s", Studname1);
    printf("\nStudent1 ID: %d%d%d", num1, num2, num3);
    printf("\n\nStudent2 Name: %s", Studname2);
    printf("\nStudent2 ID: %d%d%d", num4, num5, num6);
    return 0;
}
  • 1
    `scanf(" %c", &l1);` does not consume the `'\n'` after the character for `l1`. `fgets()` consumed the `'\n'` as an empty line. Avoid mixing `fgets()` with `scanf()`. Don't use `scanf()`. – chux - Reinstate Monica Jun 02 '21 at 15:11
  • MAybe the better duplicate is https://stackoverflow.com/questions/5918079/fgets-doesnt-work-after-scanf – William Pursell Jun 02 '21 at 15:13

0 Answers0