Reputation: 275
I'm trying to write a function to convert hex number into decimal,but I'm having issues with what I assume is error in for loop of my first function.I am unable to catch whatever character is on the end of my array and it loops one additional time.I've removed extra code and left only relevant parts.I assume this could be fixed by using get/putchar but I really wanna know what's causing it. Thanks!
#include <stdio.h>
#include <ctype.h>
#include <stdio.h>
int main(){
int check;
char num_input[20];
scanf("%s",num_input);
int hex_check(char *hex_input){
int i;
int n;
for(i=0;hex_input[i]!='\n' || hex_input[i]!=EOF;i++){
if(isxdigit(hex_input[i])!=0){
n++;
printf("\nTRUE");
}
else{
n=0;
printf("\nFALSE");
return n;
}
}
return n;
}
check=hex_check(num_input);
printf("\n%d",check);
return 0;
}
Output when inputting 123(I was using n to pass number of digits to other part of the function,0 if number is not hex):
TRUE
TRUE
TRUE
FALSE
0
Upvotes: 1
Views: 101
Reputation: 726579
This is because the condition
hex_input[i]!='\n' || hex_input[i]!=EOF
is always true: the input cannot be a '\n'
and an EOF
together at the same time.
The other issue is that you will never see an EOF
in your string; however, you will see a null terminator, i.e. '\0'
Change to
hex_input[i]!='\n' && hex_input[i]!='\0'
to fix the problem.
Another thing that you are missing is the initialization of n
: you should set it to zero before your loop starts incrementing it.
Finally, nested functions are not allowed by the ANSI standard, making your code non-portable. Consider moving the code of hex_check
to the outer level, and declare it static
to ensure that it is not visible from other modules.
Upvotes: 4