C++/plz help
Expert: Prince M. Premnath - 1/2/2009
QuestionHi
can you please help me with this code below,i want this to put the returning value of the token function in x then ask if we want to continue the loop or not,but it seems that the scanf doesn't work,can you help me plz?
#include<stdio.h>
#include<stdlib.h>
int token(char);
void main(){
int f=0,d=0;
char a=0,x=0;
while(f!=1){
x=token(a);
printf("%c\n",x);
printf("Do you want to continue?(Y/N)\n");
scanf("%d",&d);//******My problem******
printf("d=%d\n",d);
if(d=='Y')
f=0;
else if(d=='N')
f=1;
}
}
int token(char a){
printf("Enter:\n");
scanf("%c",&a);
printf("a=%c\n",a);
return a;
}
Thanx
Bita
AnswerHai dear bita !
This is a common issue for a novice programmer, even I’ve encountered these issues far past burnt my midnight oil to find the solution, after a long battle I found the solution but I couldn’t remember how :-(
Let’s come to the issue! While dealing conditions with characters this problem is quit common, so can’t we use characters any more? Yes we can, only thing you have to do is to clear the standard buffer for every cycle otherwise scanf() function will not be that much efficient for character and string input, because it assumes the past values stored in buffer!
Presenting you the modified version of your program , will do all you need !
#include<stdio.h>
#include<stdlib.h>
int token(char);
void main(){
int f=0,d=0;
char a=0,x=0;
while(f!=1){
x=token(a);
printf("x = %c\n",x);
printf("Do you want to continue?(Y/N)\n");
fflush(stdin);
scanf("%c",&d);//******My problem******
printf("d=%c\n",d);
if(d=='y')
f=0;
else if(d=='n')
f=1;
}
}
int token(char a){
printf("Enter:\n");
fflush(stdin);
scanf("%c",&a);
return a;
}
Thanks and Regards !
Prince M. Premnath