You are not logged in.

#1 2014-08-16 06:48:35

rahullfo
Member
Registered: 2014-08-16
Posts: 1

getchar() problem

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

#2 2014-08-16 11:55:45

mhogomchungu
Member
Registered: 2013-03-29
Posts: 87

Re: getchar() problem

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

#3 2014-08-16 11:56:52

Mr.Elendig
#archlinux@freenode channel op
From: The intertubes
Registered: 2004-11-07
Posts: 4,092

Re: getchar() problem


Evil #archlinux@libera.chat channel op and general support dude.
. files on github, Screenshots, Random pics and the rest

Offline

#4 2014-08-16 12:03:18

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 29,551
Website

Re: getchar() problem

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

Board footer

Powered by FluxBB