1

I am new to C and learning how to get user input. Below is my code and the execution printout. Why the char input will be auto entered and I key in age input (which is 10) and press ENTER? It won't have this problem if I place the grade input before age input.

code

//get user variable
    int age;
    printf("Enter your age: ");
    scanf("%d", &age);
    printf("You are %d years old \n", age);

    char grade;
    printf("Enter your grade: ");
    scanf("%c", &grade);
    printf("You grade is %c \n", grade);

    double gpa;
    printf("Enter your gpa: ");
    scanf("%lf", &gpa);
    printf("You gpa is %f \n", gpa);

    double name[5];
    printf("Enter your name: ");
    scanf("%s", name);
    printf("You name is %s \n", name);

console printout

Enter your age: 10
You are 10 years old
Enter your grade: You grade is

Enter your gpa: 2.5
You gpa is 2.500000
Enter your name: ofbgeowfgboe
You name is ofbgeowfgboe
Isaac
  • 155
  • 9
  • `scanf("%c", &grade);` -> `scanf(" %c", &grade);`. Also, you should `fflush(stdout)` to ensure the `printf` calls that don't end with a newline appear in the output at the expected time. – kaylum Aug 28 '21 at 06:21
  • 1
    "_learning how to get user input_" - First lesson: Check if the called function indicates success or not. TL;DR; `if(scanf(...) == the_expected_number_of_read_values) { /* success */ } else { /* fail */ }` – Ted Lyngmo Aug 28 '21 at 06:24
  • Worth noting: `double name[5];` and `scanf("%s", name);` is utterly wrong. You probably want `char name[5]; scanf("%4s", name);` (which allows for a name to be at most 4 characters long). – Ted Lyngmo Aug 28 '21 at 09:28

1 Answers1

1

You can put a getchar() after each call to scanf(). Why? scanf() left in the stdin buffer any \n (i. e, when you press Enter).

I suggest to you to use fgets() and sscanf() insted. It is safer.

GoWiser
  • 857
  • 6
  • 20