C - GetInt: Perform free-format input conversion by breaking a stream of characters into integer

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击人工智能教程

/*
 * 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

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值