Exercise 5.6. Rewrite appropriate programs from earlier chapters and exercises with pointers
instead of array indexing. Good possibilities include getline (Chapters 1 and 4), atoi, itoa,
and their variants (Chapters 2, 3, and 4), reverse (Chapter 3), and strindex and getop
(Chapter 4).
instead of array indexing. Good possibilities include getline (Chapters 1 and 4), atoi, itoa,
and their variants (Chapters 2, 3, and 4), reverse (Chapter 3), and strindex and getop
(Chapter 4).
/* getline */
int getline(char *l, int lim)
{
int c;
char *tmp = l;
for(; --lim > 0 && (c=getchar()) != EOF && c!='\n'; l++)
*l = c;
if(c=='\n')
*l++ = c;
*l = '\0';
return l - tmp;
}
/* atoi */
int atoi(char *s)
{
int number, indigit, hexdig;
if(*s++ == '0')
if(*s == 'x' || *s == 'X')
s++;
indigit = IN; // in number
number=0;
for(;indigit == IN; s++)
{
if(*s >= '0' && *s <= '9')
hexdig = *s - '0';
else if(*s >= 'a' && *s <= 'f')
hexdig = *s - 'a'+ 10;
else if(*s >= 'A' && *s <= 'F')
hexdig = *s - 'A'+ 10;
else
indigit = OUT; // out number
if(indigit == IN)
number = number*16 + hexdig;
}
return number;
}
/*itoa*/
void itoa(int n, char *s)
{
int sign;
char *t = s;
sign = n; //save sign
do
{
*s++ = abs(n % 10) + '0'; //next number
} while ((n /= 10) != 0);
if (sign < 0)
*s++ = '-';
*s = '\0';
reverse(t);
}
/* reverse */
void reverse(char *s)
{
int c;
char *t;
for(t = s + (strlen(s) - 1); s < t; s++, t--)
{
c = *s;
*s = *t;
*t = c;
}
}
/*strindex: return index of pattern in line, -1 if none*/
int strindex(char *s, char *sf)
{
char *sc = s;
char *j, *k;
for(; *s != '\0'; s++)
{
for(j = s, k = sf; *k != '\0' && *j == *k; j++, k++)
;
if(k > sf && *k == '\0')
return s - sc ;
}
return -1;
}
/* getop: get next character ot numeric operand */
#include <math.h>
int getop(char *s)
{
int c;
while((*s = c = getch()) == ' ' || c == '\t')
;
*(s+1) = '\0';
if(!isdigit(c) && c != '.' && c != '-') // not a number
return c;
if (c == '-')
{
if(isdigit(c = getch()) || c == '.')
*++s = c; //negative numbers
else
{
if(c != EOF)
ungetch(c);
return '-';
}
}
if(isdigit(c)) //collect integer part
while(isdigit(*++s = c = getch()))
;
if(c == '.') //collect fraction part
while(isdigit(*++s = c = getch()))
;
*s = '\0';
if(c != EOF)
ungetch(c);
return NUMBER;
}
Комментариев нет:
Отправить комментарий