1

Showing below is my program which takes 3 student information " id, name, and marks", in the first loop its run as expect, all variables were in order, but in the 2nd loop (and so on), the program keeps skip the gets(e[i].stname). It just prints the question about student name then jump direct to ask their 1st mark. I tried using debug but my experiences didn't help much.

#include<stdio.h>
struct stud
{
    int stno;
    char stname[20];
    int stmark[3];
};
void main()
{
    int n, m, i;
    struct stud e[3];
    for ( i = 0; i < 3; i++)
    {
        printf("enter the name of number %d student: \n", i+1);
        gets(e[i].stname);
        printf("enter the number of student number %d:\n", i+1);
        scanf_s("%d", &e[i].stno);
        for ( m = 1; m < 4; m++)
        {
            printf("enter the mark of module %d \n",m);
            scanf_s("%d", &e[i].stmark[m-1]);
        }
    }
}
Lundin
  • 195,001
  • 40
  • 254
  • 396
Khoa.Huynh
  • 41
  • 6
  • Why is this marked C++? And is using gets a requirement? – Fang Nov 21 '17 at 16:24
  • 1
    There is no function called `gets` in neither C nor C++. See [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used). In addition, consider burninating your source of learning C with fire. – Lundin Nov 21 '17 at 16:27
  • @Fang im sorry, it was the suggestion tag – Khoa.Huynh Nov 21 '17 at 16:33

1 Answers1

1

This is one of the pitfalls of mixing the scanf and gets family of functions.

The calls to scanf_s are reading a integer value. After doing so, they leave a newline in the input buffer. Subsequent calls to scanf_s are fine because the %d format specifier skips any leading whitespace characters.

The gets function however reads all characters up to the next newline. Because scanf_s left a newline in the buffer, gets reads that newline and immediately returns.

Change the gets call to scanf_s, using the %s format specifier:

scanf_s("%19s", e[i].stname, sizeof(e[i].stname));
dbush
  • 205,898
  • 23
  • 218
  • 273
  • Good answer, but please use the canonical duplicate [How to read / parse input in C? The FAQ](https://stackoverflow.com/questions/35178520/how-to-read-parse-input-in-c-the-faq) to close all questions regarding trailing line feed characters in stdin. Various flavours of this question have been asked countless times before. – Lundin Nov 21 '17 at 16:31
  • @Lundin im new to stackoverflow and programing so i will try to avoid asking common question amap. Cause i dont really know which one is common or uncommon right now. – Khoa.Huynh Nov 21 '17 at 16:46
  • @Khoa.Huynh Yeah it can be hard to determine that as a beginner. No harm done, we just don't want to keep duplicate questions around. There's a C programming FAQ under the C tag here: https://stackoverflow.com/tags/c/info – Lundin Nov 22 '17 at 07:58