练习5-1
如果符号-或+后面跟的不是数字,getint函数将把符号视为0的有效表达方式。修改该函数,将这个形式的+或者-符号重新写回到输入流。
说明:题目理解起来不是特别清晰,不知道是翻译过来的问题还是我理解的问题,参考了一下答案。
#include <stdio.h>
#include <ctype.h>
int getch(void);
void ungetch(int);
int getint(int);
int getint(int *pn)
{
int c, i, sign;
while (isspace(c = getch())) /* 跳过空白 */
;
if (!isdigit(c) && c != '+' && c != '-' && c != EOF){ /* 不是数字,+,-,结束 */
ungetch(c);
return 0;
}
sign = (c == '-') ? -1 : 1;
if (c == '+' || c == '-') {
i = c;
c = getch();
if (!isdigit(c)) { /* 符号后面的输入不是数字 */
if (c != EOF)
ungetch(c);
ungetch(i);
return c;
}
}
for (*pn = 0; isdigit(c); c = getch()) /* 字符串转换成整数 */
*pn = *pn * 10 + c - '0';
*pn *= sign;
if (c != EOF)
ungetch(c);
return c;
}
练习5-2
模仿函数getint的实现,编写一个读取浮点数的getfloat函数。getfloat函数的返回值应该是什么类型?
实现:
#include <stdio.h>
#include <ctype.h>
int getch(void);
void ungetch(int);
int getint(float *);
int getint(double *pn)
{
int c, i, sign;
float power;
while (isspace(c = getch())) /* 跳过空白 */
;
if (!isdigit(c) && c != '+' && c != '-' && c != EOF){ /* 不是数字,+,-,结束 */
ungetch(c);
return 0;
}
sign = (c == '-') ? -1 : 1;
if (c == '+' || c == '-') {
i = c;
c = getch();
if (!isdigit(c)) { /* 符号后面的输入不是数字 */
if (c != EOF)
ungetch(c);
ungetch(i);
return c;
}
}
for (*pn = 0; isdigit(c); c = getch()) /* 字符串转换成整数 */
*pn = *pn * 10 + c - '0';
if (c == '.') {
power = 1.0;
c = getch();
for (; isdigit(c); c = getch()) {
*pn = *pn * 10 + c - '0';
power *= 10;
}
*pn /= power;
}
*pn *= sign;
if (c != EOF)
ungetch(c);
return c;
}
练习5-3
用指针方式实现第二章中的函数strcat。函数strcat(s,t)将t指向的字符串复制到s指向的字符串的尾部。
代码:
void strcat(char *s, char *t)
{
while (*s++)
;
while(*s++ = *t++)
;
}
练习5-4
编写函数strend(s,t)。如果字符串t出现在字符串s的尾部,该函数返回1,否则返回0。
代码:
int strend(char *s, char *t)
{
int i = strlen(s) - strlen(t);
s += i;
for (; *s == *t; s++, t++)
;
if (*s == '\0')
return 1;
else
return 0;
}
练习5-5
实现库函数strncpy、strncat和strncmp它们最多对参数字符串中的前n个字符经行操作。
void strncpy(char *s, char *t, int n)
{
int i;
if (strlen(t) >= n)
for (i = 0; i < n; i++)
*s++ = *t++;
else
while (*s++ = *t++)
;
*s = '\0';
}
void strncat(char *s, char *t, int n)
{
int i;
while (*s++)
;
if (strlen(t) >= n) {
for (i = 0; i < n; i++)
*s++ = *t++;
} else
for (i = 0; *t != '\0'; i++)
*s++ = *t++;
*s = '\0';
}
int strncmp(char *s, char *t, int n)
{
for (; *s == *t; s++, t++)
if (*s == '\0' || --n <= 0)
return 0;
return *s - *t;
}