Link to home
Start Free TrialLog in
Avatar of old_goat_trying_to_learn
old_goat_trying_to_learn

asked on

How can I handle hex input and convert to decimal?

Hi,

I'm writing a program which will prompt the user an offset to be used to dump the contents of a file to hex. The offset is to be entered in hex. For example if they enter f I want to convert it to 15. I'm an old goat trying to learn, so be gentle. Thanks. The following is what I've been trying with no luck.

  unsigned int n;
  char line[10];
     
  printf("enter a hex\n");
 
  fgets(line, 10, stdin);      
  scanf(line,"%d", &n);
 
ASKER CERTIFIED SOLUTION
Avatar of gj62
gj62

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of old_goat_trying_to_learn
old_goat_trying_to_learn

ASKER

Thanks gj62,

I had tried that before(sorry for not mentioning it), but it didn't work. It worked once I used sscanf rather than scanf. If I may ask...why?

Thanks
Sorry, should have seen that to begin with...

scanf reads from stdin (the keyboard, in most cases)

sscanf reads from a string.

So, when you said:

scanf(line,"%x", &n);

it was actually looking in line for the format string...

in

sscanf(line,"%x", &n);

it knew that line was the input buffer.

Functions that have a variable number of args can't do alot of checking, and that's a common bug to have happen...