Thread: (not sure) scanf_s or gets_s problem

  1. #1
    Registered User
    Join Date
    Jan 2018
    Posts
    1

    (not sure) scanf_s or gets_s problem

    Hello.

    I made a program like this:

    Code:
    #include <stdio.h>
    
    
    typedef struct student {
    char name[20];
    int id;
    int grade;
    } student;
    
    
    int main() {
    student p;
    
    
    while (1) {
    printf("type a name: ");
    gets_s(p.name, 19);
    
    
    if (*p.name == 'q') break;
    
    
    printf("type the id: ");
    scanf_s("%d", &p.id, sizeof(int));
    
    printf("type the grade: ");
    scanf_s("%d", &p.grade, sizeof(int));
    
    
    switch (p.grade / 5) {
    case 20:
    case 19: printf("A+\n"); break;
    case 18: printf("A\n"); break;
    case 17: printf("B+\n"); break;
    case 16: printf("B\n"); break;
    case 15: printf("C+\n"); break;
    case 14: printf("C\n"); break;
    case 13: printf("D+\n"); break;
    case 12: printf("D\n"); break;
    default: printf("F\n");
    }
    }
    
    
    return 0;
    }
    I expect the program continues to get "new person" in each cycle, but the result looks like this:

    type a name: iam
    type the id: 1994
    type the grade: 97
    A+
    type a name: type the id: myname
    type the grade: A+
    type a name: type the id: hello
    type the grade: A+
    type a name: type the id: what's going on?
    type the grade: A+
    type a name: type the id:


    Would you plz explain what the problem is?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Unformatted input like gets_s does not play nice with formatted input like scanf_s. The thing is, the formatted input consumes the minimum number of characters of input. Typically this means leaving the trailing \n for something else to read.

    But \n is exactly what gets_s needs to return immediately.

    The solution is to use ONE input method consistently through the program.

    Personally I use fgets() and scanf()
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Scanf Vs Scanf_s
    By Rednally in forum C Programming
    Replies: 8
    Last Post: 03-29-2016, 07:27 PM
  2. problem with scanf_s
    By birdog9999 in forum C Programming
    Replies: 8
    Last Post: 05-19-2015, 12:25 PM
  3. using scanf_s in a function
    By Vorthaine in forum C Programming
    Replies: 41
    Last Post: 11-12-2013, 04:47 PM
  4. scanf_s into array
    By JamesY in forum C++ Programming
    Replies: 4
    Last Post: 11-02-2011, 07:21 AM
  5. How to use gets_s
    By gwarf420 in forum C Programming
    Replies: 26
    Last Post: 05-24-2008, 03:29 AM

Tags for this Thread