-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
80 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |