Hi everyone, I'm new to C (within the past week or so) and I have a question about arrays.
I'm attempting to write a Hex to Integer (hex to decimal) function, while checking to make sure input is correct. My problem is checking to make sure all chars entered are in the set "0123456789abcdefABCDEF".
The error occurs when a value of, say 'A', is entered (hex value of A = 10), the for loop will continue to verify while i<max, and jump out.
is there any way to find out how many elements were added to the array when using scanf?
here's my code:
Code:
#include <stdio.h>
#include <string.h>
int htoi(char s[])
{
int x;
sscanf(s, "%x", &x);
printf("%u\n", x);
return x;
}
int main()
{
const int max= 10;
char s[max];
int i;
const char *legal= "0123456789abcdefABCDEF";
printf("enter hex value (max size %d): ", max);
scanf("%s", s);
if('O'==s[0]) //Ox or OX prefix is present, remove it.
{
for(i=0; i<max-1; i++)
{
s[i]= s[i+2];
}
i=0;
}
for(i=0; i<max; i++)
{
if(!strchr(legal, s[i]))
{
printf("Illegal hexidecimal value.");
return 0;
}
}
return htoi(s);
}