solutions to 04-01 and 04-02

master
Tibor Bizjak 2023-07-04 10:28:05 +02:00
parent 824f409213
commit c8cdc37824
2 changed files with 99 additions and 0 deletions

View File

@ -0,0 +1,40 @@
#include <stdio.h>
#include <string.h>
#define STRING "test string with lost of stuff"
int strindex(char source[], char searchfor[]);
/* pass optional searchfor arg to strindex with STRING, pretty print result */
int main(int argc, char *argv[])
{
char s[] = STRING;
char *t = (argc > 1) ? argv[1] : "est";
int i = strindex(s, t);
if (i < 0) {
printf("no match\n");
return 1;
}
printf("%s\n", s);
while (i--)
putchar(' ');
printf("^\n");
return 0;
}
/* strindex: return index of the righmost occurence of t in s, -1 if none */
int strindex(char s[], char t[])
{
int i, j;
const int tlen = strlen(t);
j = tlen - 1;
for (i = strlen(s)-1; i; i--)
if (s[i] != t[j])
j = tlen - 1;
else if (!(j--)) // match found
return i;
return -1;
}

View File

@ -0,0 +1,59 @@
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#define DEC_SEP X('.') X(',')
#define EXP_SEP X('e') X('E')
double atof(char *s);
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("error: expected argument\n");
return 1;
}
printf("%f\n", atof(argv[1]));
return 0;
}
/* macros for atof */
#define SIGN(s) \
((*s == '-') ? (s++, -1) : ((*s == '+') ? (s++, 1) : 1))
#define ATOI(s, x, ...) \
for (; isdigit(*s); s++, ##__VA_ARGS__) \
x = 10 * x + (*s - '0')
/* atof: convert string s to double */
double atof(char s[])
{
double val;
while (isspace(*s))
s++;
/* integer part */
int sign = SIGN(s);
ATOI(s, val);
#define X(sep) *s != sep &&
if (DEC_SEP 1) return sign * val;
#undef X
s++;
/* fractional part */
int exp = 0;
ATOI(s, val, exp--);
val *= sign * pow(10, exp);
#define X(sep) *s != sep &&
if (EXP_SEP 1) return val;
#undef X
s++;
/* exponent */
sign = SIGN(s);
exp = 0;
ATOI(s, exp);
return val * pow(10, sign * exp);
}