Search code examples
cscanf

I don't know why it would not function as it should be, I used gets() and fgets(), the same result happen


#include <stdio.h>
#include <string.h>

struct student{
    char name[20];
    char studentNumber[5];
    int yearOfBirth;
    float avgPoint;
};

int main(){
    struct student hssv[3];
    int i;
//input info for students, this case its 3 students
    for(i=0; i<3; i++){
        printf("Input element value: ");
        printf("\nInput your name: ");
        fflush(stdin);
        fgets(hssv[i].name, sizeof(hssv[i].name), stdin); //this line doesnt work for the loop
        printf("Input your student code: ");
        fflush(stdin);
        fgets(hssv[i].studentNumber, sizeof(hssv[i].studentNumber), stdin);
        printf("Input your year of birth: ");
        scanf("%d", &hssv[i].yearOfBirth);
        printf("Input your point: ");
        scanf("%f", &hssv[i].avgPoint);
    }
//output info
    for(i=0; i<3; i++){
        printf("\nOutput element value: ");
        printf("\nYour name: %s", hssv[i].name);
        printf("\nInput your student code: %s", hssv[i].studentNumber);
        printf("\nInput your year of birth: %d", hssv[i].yearOfBirth);
        printf("\n\nInput your point: %f", hssv[i].avgPoint);
    }

    return 0;
}

I don't know why it would not function as it should be, I used get() but then there is a warning saying I should use fgets(). Then I looked it up, and used it but the same result keep happening. The input for name does not work for 2nd onward in the loop, I guess it's buffer overflow ? but Im using fflush() already. Please help...


Solution

  • Don't use gets(). It's been withdrawn.

    fgets() will stop at the end of hssv[i].name (that's what the parameter taking sizeof(hssv[i].name) is for). gets() will keep going if the user types too much and trample on whatever comes after. Servers have been commandeered this way.

    Your code isn't working because the scanf() call left a newline in the input buffer. There are ways to solve this; my recommendation is to never use scanf but only sscanf like so:

    char linebuf[21]; // Reuse for all number reads
    // ...
    fgets(linebuf, sizeof(linebuf), stdin);
    sscanf(linebuf, "%d", &hssv[i].yearOfBirth);
    

    Get rid of fflush(stdin);; it doesn't always work.

    Note to mod: while we normally delete thank you comments; in this case trying to do so would make the comment thread make no sense.