C++/plz help

Advertisement


Question
Hi

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

Answer
Hai 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

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Prince M. Premnath

Expertise

Years of research in C/C++ Will bring you all facts regarding , OOPS , SVGA , MOUSE , BIOS , IVT , Feel free to query me :-)

Experience

More than 5 years

Education/Credentials
MCA

©2016 About.com. All rights reserved.