0

Hi All,

I am trying to convert an inputted user string into an array of ints, that will be used as hexadecimals. The user will only enter hex in the string.

Does anyone know why the below code produces the following output. The first entry is incorrect, all the rest are correct.

I entered 0123456789abcdef

22ff601 2 3 4 5 6 7 8 9 a b c d e f

char string[16];
gets(string);

for(x=1;x<16;x++)
{
                 if(string[x]<58)
                 {//printf("%x\t", string[x]);
                 string[x]-=48;
                 printf("%x\t", string[x]);
                 }
                 else if(string[x]<91)
                 {//printf("%x\t", string[x]);
                      string[x]-=55;
                 printf("%x\t", string[x]);
                 }
                 else
                 {
                     string[x]-=87;
                     printf("%x\t", string[x]);
                 }
}
2
Contributors
1
Reply
2
Views
10 Years
Discussion Span
Last Post by WaltP
0

#1- gets() is a dangerous function, as you can see by the link
#2- If you enter 16 characters, you just blew past your array bounds when gets() adds the required 0 in the 17th location.
#3- change each printf() so you can tell which one is outputting the junk. then we can see where the problem is.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.