取输入中的下一个整数

版权声明:原创请勿随意转载。 https://blog.csdn.net/yjysunshine/article/details/81505381

《C程序设计语言》P96

#include <stdio.h>
#include <ctype.h>//是isspace()  , isdigit()函数的头文件
#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 =='+')
        c = getch();
    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;
}
 

猜你喜欢

转载自blog.csdn.net/yjysunshine/article/details/81505381