-1

I wrote a small program in c programming language. The program just get students data and save them in the struct fields. After that I was hoping to print the data but it seems that the code is not working properly.

I wrote that in the visual studio 17 ide.

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

struct Students
{
    char Student_ID[12];
    char Student_FirstName[20];
    char Student_LastName[20];
    char Student_StudyField[32];
    int Student_Level;
};

int main()
{
    struct Students STU1;

    printf("Student ID: ");
    scanf_s("%11s", STU1.Student_ID, sizeof(STU1.Student_ID));
    printf("Student first name: ");
    fgets(STU1.Student_FirstName, sizeof(STU1.Student_FirstName), stdin);
    printf("Student last name: ");
    fgets(STU1.Student_LastName, sizeof(STU1.Student_LastName), stdin);
    printf("Student study field: ");
    fgets(STU1.Student_StudyField, sizeof(STU1.Student_StudyField), stdin);
    printf("Student level: ");
    scanf_s("%2d", STU1.Student_Level, sizeof(STU1.Student_Level));

    printf("\n");
    printf("Student ID: %s\n", STU1.Student_ID);
    printf("Student first name: %s\n", STU1.Student_FirstName);
    printf("Student last name: %s\n", STU1.Student_LastName);
    printf("Student study field: %s\n", STU1.Student_StudyField);
    printf("Student level: %d\n", STU1.Student_Level);

    return 0;
}

Output:

Student ID: 12345678900
Student first name: Tom
Student last name:
Student ID: 12345678900
Student first name: Tom
Student last name:
HiDD3N
  • 29
  • 2
  • 7
  • There's probably a good duplicate somewhere, but to summarize the `scanf_s` call doesn't read the newline that the `Enter` key added in the input buffer. That newline is instead read (and interpreted as an empty line) by the next `fgets` call. – Some programmer dude Oct 17 '19 at 17:14
  • There's no duplicate. How to get int data format with fgets? – HiDD3N Oct 17 '19 at 18:29
  • In [the `c` tag wiki](https://stackoverflow.com/tags/c/info) there's a FAQ list, where you can find a link to [scanf() leaves the new line char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer), which is the canonical duplicate. – Some programmer dude Oct 18 '19 at 06:05

1 Answers1

0

Temporary buffer + gets + sscanf should work

char buff[256] ;
STU1.Student_Level = 0 ;     // Or other default
if ( fgets(buff, sizeof(buff), stdin) ) {
    int v ;
    if ( sscanf(buff, "%d", &v) == 1 ) {
        STU1.Student_Level = v ;
    } ;
} ;
dash-o
  • 13,723
  • 1
  • 10
  • 37