U E D R , A S I H C RSS

Our Major Lang IsCAndCPlus Plus/print/이상규

~cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <ctype.h>

void ftoa(double f, char *str)
{
	int dec, sign;
	char *buf = fcvt(f, 5, &dec, &sign);

	if(sign == 0)
		strncpy(str, buf, dec);
	else if(sign == 1)
	{
		strcpy(str, "-");
		strncat(str, buf, dec);
	}
	str[dec + sign] = '\0';
	strcat(str, ".");
	strcat(str, &buf[dec]);
}

void print(const char *format, ...)
{
	const char *c = format;
	char str[1024];

	va_list args;
	va_start(args, format);

	while(*c != '\0')
	{
		if(*c == '%')
		{
			c++;

			int align = 0;
			if(isdigit((int)*c))
			{
				align = *c - '0';
				c++;
			}
			
			if(*c == 'd')
			{
				int d = va_arg(args, int);
				itoa(d, str, 10);
			}
			else if(*c == 's')
			{
				char *s = va_arg(args, char *);
				strcpy(str, s);
			}
			else if(*c == 'f')
			{
				double f = va_arg(args, double);
				ftoa(f, str);
			}

			int space = align - strlen(str);
			for(int i = 0 ; i < space ; i++)
				fputc((int)' ', stdout);

			fputs(str, stdout);
		}
		else if(*c == '@')
		{
			c++;

			fputs("{ ", stdout);
			if(*c == 'd')
			{
				int *darr = va_arg(args, int *);
				int len = va_arg(args, int);

				for(int i = 0 ; i < len ; i++)
				{
					itoa(darr[i], str, 10);
					fputs(str, stdout);
					if(i < len - 1)
						fputs(", ", stdout);
				}
			}
			else if(*c == 's')
			{
				char **sarr = va_arg(args, char **);
				int len = va_arg(args, int);

				for(int i = 0 ; i < len ; i++)
				{
					fputs(sarr[i], stdout);
					if(i < len - 1)
						fputs(", ", stdout);
				}
			}
			else if(*c == 'f')
			{
				double *farr = va_arg(args, double *);
				int len = va_arg(args, int);

				for(int i = 0 ; i < len ; i++)
				{
					ftoa(farr[i], str);
					fputs(str, stdout);
					if(i < len - 1)
						fputs(", ", stdout);
				}
			}
			fputs(" }", stdout);
		}
		else
			fputc((int)*c, stdout);

		c++;
	}

	va_end(args);
}

void main()
{
	{
		int a = 10;
		char *b = "example";
		double c = -10.5;
		print("number: %d, string: %s, real number: %f\n", a, b, c);
	}
	{
		int a[3] = { 1, 2, 3 };
		char *b[2] = { "abc", "def" };
		double c[5] = { 1.543, 34.34, 65.34, 235.35, 76.46 };
		print("array: @d\n", a, 3);
		print("array: @s\n", b, 2);
		print("array: @f\n", c, 5);
	}
	{
		int a = 123;
		int b = 12345;
		int c = 12345678;
		print("number: %5d\n", a);
		print("number: %5d\n", b);
		print("number: %5d\n", c);
	}
}
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2009-05-27 07:09:19
Processing time 0.0084 sec