C-GetInt:文字のストリームを整数に分割することにより、自由形式の入力変換を実行します

大きな牛の人工知能のチュートリアルを共有します。ゼロベース!わかりやすい!面白くてユーモラス!あなたも人工知能チームに参加してください!http://www.captainbed.netをクリックしてください

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

*/

 

おすすめ

転載: blog.csdn.net/chimomo/article/details/114537657