分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击人工智能教程
/*
* GetInt: Perform free-format input conversion by breaking a stream of characters
* into integer values, one integer per call.
*
* GetInt.c - by FreeMan
*/
#include <ctype.h>
#include <stdio.h>
#define BUFFERLENGTH 100
int GetCh(void);
void UngetCh(int);
int buf[BUFFERLENGTH];
int nfp = 0;
void ViewBuffer(void)
{
int i;
printf("\nbuffer:\n");
for (i = nfp - 1; i >= 0; i--)
{
printf("%d\n", buf[i]);
}
}
int GetCh(void)
{
return (nfp > 0) ? buf[--nfp] : getchar();
}
void UngetCh(int c)
{
if (nfp < BUFFERLENGTH)
{
buf[nfp++] = c;
}
else
{
printf("error: ungetch buffer overflow\n");
}
}
int GetInt(int *pn)
{
int c, sign;
while (isspace(c = getchar()))
;
if (!isdigit(c) && c != EOF && c != '+' && c != '-')
{
UngetCh(c);
return 0;
}
sign = (c == '-') ? -1 : 1;
if (c == '+' || c == '-')
{
c = GetCh();
if (!isdigit(c))
{
UngetCh(sign == -1 ? '-' : '+');
return 0;
}
}
for (*pn = 0; isdigit(c); c = GetCh())
{
*pn = *pn * 10 + (c - '0');
}
*pn *= sign;
if (c != EOF)
{
UngetCh(c);
}
return c;
}
int main()
{
int x, retval, * px;
px = &x;
retval = GetInt(px);
printf("retval = %d, x = %d\n", retval, x);
ViewBuffer();
return 0;
}
// Input:
/*
-123456
*/
// Output:
/*
retval = 10, x = -123456
buffer:
10
*/