Skip to content

Instantly share code, notes, and snippets.

@Learath2
Last active August 29, 2015 14:04
Show Gist options
  • Save Learath2/c903f8036b411b496f07 to your computer and use it in GitHub Desktop.
Save Learath2/c903f8036b411b496f07 to your computer and use it in GitHub Desktop.
K&R2 Exercise 2-3
/*K&R2 Exercise 2-3 "htoi"*/
#include <stdio.h>
#include <ctype.h>
int htoi(char[]);
int getl(char[], int);
int main()
{
char s[20];
int c;
while((c = getl(s, 20)))
printf("%d\n", htoi(s));
}
int getl(char s[], int lim)
{
int c, i;
for(i = 0; i < lim-1 && (c = getchar()) != EOF && c !='\n'; ++i)
s[i] = c;
if(c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
int htoi(char s[])
{
int i, n;
n = 0;
for(i = 0; s[i] != '\0'; i++)
s[i] = tolower(s[i]);
for(i = 0; s[i] != '\0'; i++)
if(isdigit(s[i]))
n = 16 * n + (s[i] - '0');
else if(s[i] >= 'a' && s[i] <= 'f')
n = 16 * n + (s[i] - 87);
else if(s[i] != 'x' || s[i] != '\n')
return -1;
return n;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment