Skip to content

Commit

Permalink
exercise 2.02 2.03
Browse files Browse the repository at this point in the history
  • Loading branch information
jlzhjp committed Dec 4, 2024
1 parent 1a92ec5 commit a678786
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
42 changes: 42 additions & 0 deletions chapter_2/exercise_2_02.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include <stdio.h>

#define MAXLINE 32

int _getline(char line[], int maxline);

/* Write a loop equivalent to the for loop above without using && or ||. */
int main()
{
char s[MAXLINE];
while (_getline(s, MAXLINE)) {
printf("%s", s);
}
return 0;
}

int _getline(char s[], int lim)
{
int c, i;

i = 0;
for (;;) {
if (i < lim - 1) {
if ((c = getchar()) != EOF) {
if (c != '\n') {
s[i] = c;
++i;
continue;
}
}
}
break;
}

if (c == '\n') {
s[i] = c;
++i;
}

s[i] = '\0';
return i;
}
38 changes: 38 additions & 0 deletions chapter_2/exercise_2_03.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int htoi(char s[], int limit);

int main()
{
printf(" 0xff - %d\n", htoi("0xff", INT_MAX));
printf("0x88fe - %d\n", htoi("0x88fe", INT_MAX));
return 0;
}

int htoi(char s[], int limit)
{
if (s[0] != '0' || (s[1] != 'x' && s[1] != 'X')) {
fprintf(stderr, "hex format error\n");
exit(1);
}

int res = 0;
int base = 1;
for (size_t i = strnlen(s, limit) - 1; i >= 2; --i, base *= 0x10) {
if ('0' <= s[i] && s[i] <= '9') {
res += (s[i] - '0') * base;
} else if ('a' <= s[i] && s[i] <= 'f') {
res += (s[i] - 'a' + 10) * base;
} else if ('A' <= s[i] && s[i] <= 'F') {
res += (s[i] - 'A' + 10) * base;
} else {
fprintf(stderr, "hex format error\n");
exit(1);
}
}

return res;
}

0 comments on commit a678786

Please sign in to comment.