You are not logged in.
Pages: 1
Hi All,
I am a complete newbie and started learning 'C'.
I am trying to create a sample program to calculate percentage of a student.The problem is that when enter the student name after running the code below the program exists without asking for rest of the input values.
I don't understand where am I going wrong.
Please help!
#include <stdio.h>
#include <conio.h>
void main()
{
float percentage,total,english,science,maths,history,geography;
char student;
printf("Enter Student Name:");
scanf_s("%c",&student);
printf("Enter marks obtained by the student in english:");
scanf_s("%d",&english);
printf("Enter marks obtained by the student in science:");
scanf_s("%d",&science);
printf("Enter marks obtained by the student in maths:");
scanf_s("%d",&maths);
printf("Enter marks obtained by the student in history:");
scanf_s("%d",&history);
printf("Enter marks obtained by the student in geography:");
scanf_s("%d",&geography);
total = english+science+maths+history+geography;
percentage=total/500*100;
printf("Name of the Student = %c \nPercentage = %f",student,percentage);
getchar();
}
Offline
Its important to know that the keyboard is a buffered device and scanf among other functions
reads from the buffer until there is nothing to read and then block waiting for more data.
The reason why your program appeared to just went through is because you typed a name on the keyboard
and the name was buffered.But then you only read one character for the name and the rest of the name
characters remained in the buffer and your follow up scanf_s just took data from the buffer since they
found the buffer to not be empty.
The above explanation is also applicable with that getchar(),that command will block waiting for
user input only if it found the keyboard buffer to be empty.
Try to modify your program with these two lines and try again
char student[1032];
scanf_s("%s",student);
Last edited by mhogomchungu (2014-08-16 11:59:59)
Offline
Evil #archlinux@libera.chat channel op and general support dude.
. files on github, Screenshots, Random pics and the rest
Offline
Is this in archlinux? Is this even in linux? Are you cross compiling for windows/wine?
"UNIX is simple and coherent..." - Dennis Ritchie, "GNU's Not UNIX" - Richard Stallman
Offline
Pages: 1