I’m new to c programming and I’m facing this problem with my program
I have a loop that gets a char form the input buffer
while(c = getchar()){
if(c == '\n') break;
if(c == '1') Add();
if(c == '2') getInput(); // this is where the headache starts
....
}
here is the getInput() function
void getInput()
{
char ch = getchar();
if(ch == '1') doSomething();
....
}
but when calling getchar() from the getInput() function it only gets characters that were left in the input buffer from the last call of getchar(). and what i want it to do is to get newly typed characters.
I’ve been googling for two hours for a decent way to clear the input buffer but nothing helped. So a link to a tutorial or an article or something is very appreciated and if there’s another way to implement this then please tell me.
First of all there will be
==comparison operator rather than=assignment operator in theifcondition in this code.And for stop taking input try
EOFwhich from keyboard can be given by prssingCTRL+D.EDIT : The problem is with the
\nwhich is actually taken as input when you pressENTERkey on the key board. So change just one line of code.if (c ==\n) break;toif (c == EOF ) break;and as I saidEOFis the end of input.Then your code will work fine.
Flow of code :
but after changing the code as I said , this should work.
NOTE: To understand code flow and for debugging purposes it’s best practice to put
printf()in various places in functions and see the output as which lines are executing and which are not.