C - GetInt: realiza una conversión de entrada de formato libre dividiendo un flujo de caracteres en números enteros

Comparte el tutorial de inteligencia artificial de una gran vaca. ¡Basado en cero! ¡Fácil de entender! ¡Divertido y chistoso! ¡Espero que también te unas al equipo de inteligencia artificial! Haga clic en 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

*/

 

Supongo que te gusta

Origin blog.csdn.net/chimomo/article/details/114537657
Recomendado
Clasificación