PDA

View Full Version : C Programming - VERY simple password entry program...



squareff255
March 2nd, 2011, 11:15 AM
Why won't this work!? Every time I run it, it prints out: Invalid, even if I put in the correct pin...



#include <stdio.h>

int main(void)
{
float number = 042646;
int pass;
printf("Enter the PIN.\n");
scanf("%d", &pass);

if (pass == number)
{
printf("Correct\n");
}
else
{
printf("Invalid\n");
}
return 0;
}

Tony Flury
March 2nd, 2011, 12:31 PM
Why won't this work!? Every time I run it, it prints out: Invalid, even if I put in the correct pin...



#include <stdio.h>

int main(void)
{
float number = 042646;
int pass;
printf("Enter the PIN.\n");
scanf("%d", &pass);

if (pass == number)
{
printf("Correct\n");
}
else
{
printf("Invalid\n");
}
return 0;
}



have you actually printed out the enetered "pass" and your stored "number" when you do the comparison ?

A few things spring to mind :

1) comparing a float to an int - because of how floats are stored, there might be a chance that your "042646" is not actually stored accurately - it might be stored as 424645.9999999999 - which of course wont compare with the int (== means exactly equal and is rarely a good idea with floats) - consider storing both values as ints.

2) Does the leading zero on your stored number do something else to the number (is that the inidication that the number following is Octal - I might be wrong).

3) since the actual value is irrelevant, and you are actually interested that the user eneters the right set of characters - maybe you should be storing and fetching chars, and using character or string comparisons.

sanderj
March 2nd, 2011, 12:55 PM
First of all: is this your homework we're doing?

Comparing an int with a float? Does that work in C? I guess not.

And the leading 0 in an int will of course disappear. You can check yourself with


printf("The number is: %d\n",number);


Solution: put both number and pass in string (char[20]), and use a string compare (strcmp?).


EDIT: after posting this, I saw you had already received about the same answer.

bapoumba
March 2nd, 2011, 02:35 PM
Moved to PT.

Queue29
March 2nd, 2011, 04:27 PM
Tony Flury was on the right track about the leading zero:



#include <stdio.h>

int main() {
float n = 042646;
printf("n: %f\n", n);
return 0;
}



$ ./a.out
n: 17830.000000

Arndt
March 2nd, 2011, 04:40 PM
Comparing an int with a float? Does that work in C? I guess not.


Of course it works, in some sense (otherwise there would be a compiler error), but to know exactly what happens, consult the language reference.

Tony Flury
March 2nd, 2011, 05:42 PM
Tony Flury was on the right track about the leading zero:



#include <stdio.h>

int main() {
float n = 042646;
printf("n: %f\n", n);
return 0;
}



$ ./a.out
n: 17830.000000


Uggh - obscure C knowledge dragged up from about 15 years ago - so why can't i remember my niece's birthdays :-(

Thanks for confirming though.