-
isalpha
why does this function crash my program :(
Code:
int checkPrice (int *num)
{
scanf ("%d", num);
while (isalpha (*num))
{
fflush (stdin);
printf("Only numerals allowed\n");
printf("Please re-input the price: ");
scanf ("%d", num);
return 0;
}
fflush (stdin);
return 1;
}
num is being passed by reference..
basically, it works if i input a number but if i input a character it crashes :( and thats the exact thing i want to test in the program..
any other ways around it
:)
-
It works fine to me! can we see the full code?!
why did u include return 0 in the while loop?!
-
Re: isalpha
my friend tested a number with isalpha and it worked and i did almost same thing and it didnt... point being that isalpha can test integers :)
-
Quote:
Originally posted by Salem
isalpha tests characters, not numbers
Code:
while ( scanf("%d", num ) != 1 ) {
while ( getchar() != '\n' ); // better than fflush(stdin)
printf("Only numerals allowed\n");
printf("Please re-input the price: ");
}
i dont quite get ur first line of code...
what happens if a user inputs 22442a
will that line of code work for that
-
Salem, in your first line of code:
Quote:
Code:
while ( scanf("%d", num ) != 1 ) {
while ( getchar() != '\n' ); // better than fflush(stdin)
printf("Only numerals allowed\n");
printf("Please re-input the price: ");
}
should it not read:
Code:
while (scanf ("%d", &num) !=1 ) {
/* rest of code here */
I always thought the & was necessary when using scanf?!?!:confused:
-
num is a pointer which contain an address therefore there is no need for &!
-
Thankyou for clearing that up Lazystudent!:D
-
whoa
salem dude, u r a genius :)
but u know what even though it works, i still dont get why should it keep reading till != 1 ??? :)
-
i read the C reference manual but it didnt make sense till u gave ur explanation
thanks mate :)
-
Of course, it's quite possible that the whole reason your code was crashing was this line:
fflush (stdin);
After all, it's undefined. Theoreticly, it could crash your program.
Quzah.