www.digitalmars.com         C & C++   DMDScript  

D - type checking problem?

reply "Andrew Edwards" <aedwards spamfreeamerica.com> writes:
The following yields incorrect result when characters are inputed instead of
integers.

import stream;

int main()
{
  const int answer = 10;
  int guess;

  printf("Pick a number: ");
  scanf("%d", &guess);

  if(answer == guess)
  {
    printf("Answer = %d.", guess);
  }
  else if(answer > guess)
  {
      printf("Answer > guess.");
  }
  else if(answer < guess)
  {
      printf("Answer < guess.");
  }
  else
  {
    printf("That wasn't a number.");
  }

  return 0;
}
Jan 16 2003
parent J C Calvarese <jcc-47 excite.com> writes:
If you change "guess" to a float, I think it works as expected. 
Apparently, integers default to 0 when a non-number is given.  Try this:

import stream;

int main()
{
   const int answer = 10;
   float guess;

   printf("Pick a number: ");
   scanf("%f", &guess);

   if(answer == guess)
   {
     printf("Answer = %f.", guess);
   }
   else if(answer > guess)
   {
       printf("Answer > guess.");
   }
   else if(answer < guess)
   {
       printf("Answer < guess.");
   }
   else
   {
     printf("That wasn't a number.");
   }

   return 0;
}


Andrew Edwards wrote:
 The following yields incorrect result when characters are inputed instead of
 integers.
 
 import stream;
 
 int main()
 {
   const int answer = 10;
   int guess;
 
   printf("Pick a number: ");
   scanf("%d", &guess);
 
   if(answer == guess)
   {
     printf("Answer = %d.", guess);
   }
   else if(answer > guess)
   {
       printf("Answer > guess.");
   }
   else if(answer < guess)
   {
       printf("Answer < guess.");
   }
   else
   {
     printf("That wasn't a number.");
   }
 
   return 0;
 }
 
 

Jan 16 2003