Home > Net >  Code::Blocks is not taking in all the required inputs
Code::Blocks is not taking in all the required inputs

Time:04-01

I am new to programming and this website, so sorry if this question has been asked before. I recently started learning C from online sources. I was watching C's tutorial on freecodecamp.org's YouTube channel and during the input section of the video, I tried to input many data types as show in the video. The program skips over the grade part of the input. I don't know why it's the case.

Here is the code of what I have done -:

#include <stdio.h>

int main() 

{ 

char name[25];

printf("Enter your name : ");
scanf("%s", name);
printf("\nYour name is : %s\n", name);

char grade;

printf("\nEnter your grade : ");
scanf("%c", &grade);
printf("\nYour grade is : %c", grade);

int age;

printf("\n\nEnter your age : ");
scanf("%d", &age);
printf("\nYou are %d years old.", age);


double gpa;

printf("\n\nEnter your gpa : ");
scanf("%lf", &gpa);                        /* lf is used in input and f in output */
printf("\nYour gpa is : %f\n", gpa);




return 0;

}

When I run the program, it skips over the grade portion and does not take in the grade as input. I tried to adjust it by putting the grade input on top of the code sequence and then it worked. But when I entered another input sequence of name, it returned back to the same problem.

Here is the output -:

Output

I don't know why this is happening. I would be happy if someone can help me out here.

Thank You.

I tried the above and the result was what I have shown.

Note -: When I shifted the grade sequence in the code to the top, it works. I don't know why it's happening because I may not always input grade first.

CodePudding user response:

Reading your name with scanf leaves the \n in the input buffer.

If you try to read the grade via

scanf("%c", &grade);

you will consume that \n instead of reading new input.

To avoid this, use

scanf(" %c", &grade);

(mind the space before %c). The space will cause scanf to skip any whitespace and then ask for new input.

CodePudding user response:

Write scan f two times in a row

printf("\nEnter your grade : ");
scanf("%c", &grade);
scanf("%c", &grade);
printf("\nYour grade is : %c", grade);

Basically when you hit enter it gets picked up into variable grade, because enter or new line is also a character.

CodePudding user response:

You are trying to work with char and char[]. So when we need to accept multiple inputs based on char, you should use fflush(stdin); before scanning for an input. This will help you to accept all the inputs separately.

  •  Tags:  
  • c
  • Related