《C程序设计语言》
5-1 在上面的例子中,如果符号+或- 后面紧跟的不是数字,getint函数将把符号视为数字0的有效表达方式。修改该函数,将这种形式的+或- 符号重新写回到输入流中。
#include <stdio.h>
#include <ctype.h>
#define SIZE 100
#define BUFSIZE 100
int bufp = 0;//缓存区指针
int buf[BUFSIZE];//缓存区
int getint(int *);
int getch();
void ungetch(char );
/*取输入中的下一个整数*/
int main()
{
int n, array[SIZE];
for(n = 0; n < SIZE && getint(&array[n]) != EOF; n++)
printf("%d ", array[n]);
return 0;
}
int getint(int *ch)
{
char c;
int sign;
while(isspace(c = getch()))
;
if(c != EOF && c != '+' && c != '-' && !isdigit(c)){
ungetch(c);
return 0;
}
sign = ((c == '-')? -1: 1);
if(c == '-' || c =='+'){
char sign2 = c;
c = getch();
if(!isdigit(c)){
*ch = 0;
if(c != EOF)
ungetch(c);
ungetch(sign2);
return 0;
}
}
for(*ch = 0; isdigit(c);c = getch()){
*ch = *ch * 10 + (c - '0');
}
*ch *= sign;
if(c != EOF)
ungetch(c);
return c;
}
int getch()
{
if(bufp > 0)
return buf[--bufp];
else
return getchar();
}
void ungetch(char c)
{
if(bufp >= BUFSIZE)
printf("the buf is full");
else
buf[bufp++] = c;
}