코드 ¶
~cpp
#include <stdio.h>
#include <stdarg.h>
#include <math.h>
void PrintNumber(int leftGab, int number, double lowNumber)
{
//// 음수처리 ////
if (0 > number || 0 > lowNumber)
{
fputchar('-');
number = abs(number);
lowNumber = abs(lowNumber);
}
int numberSize = 0;
for (int tempNumber = number; tempNumber > 0; ++numberSize)
tempNumber /= 10;
int powNumber = (int)pow((int)10, numberSize);
//// 공백을 출력한다. ////
for (register int i = 0; i < leftGab - numberSize; ++i)
fputchar(' ');
//// 정수부의 숫자를 출력한다. ////
for (register int i = 0; i < numberSize; ++i)
{
fputchar((number % powNumber) / (powNumber / 10) + '0');
powNumber /= 10;
}
//// 소수부의 숫자를 출력한다. ////
if (0 != lowNumber)
{
fputchar('.');
while(0 != lowNumber)
{
lowNumber *= 10;
int printNumber = (int)lowNumber;
fputchar(printNumber + '0');
lowNumber -= printNumber;
}
}
}
void print(const char* outData, ...)
{
va_list variables;
va_start(variables, outData);
for (register int readPoint = 0; 0 != outData[readPoint]; ++readPoint)
{
if ('%' == outData[readPoint])
{
++readPoint;
//// 띄울 칸의 크기를 정합니다. ////
int spaceSize = 0;
for (; '0' <= outData[readPoint] && '9' >= outData[readPoint]; ++readPoint)
spaceSize = spaceSize * 10 + (outData[readPoint] - '0');
//// 인자에 맞게 출력을 합니다. ////
if ('d' == outData[readPoint])
{
PrintNumber(spaceSize, va_arg(variables, int), 0);
}
else if ('f' == outData[readPoint])
{
double variableDouble = va_arg(variables, double);
PrintNumber(spaceSize, (int)variableDouble / 1 , variableDouble - (int)variableDouble);
}
else if ('s' == outData[readPoint])
{
fputs(va_arg(variables, const char*), stdout);
}
}
else if ('@' == outData[readPoint])
{
++readPoint;
fputchar('{');
//// 인자에 맞게 출력을 합니다. ////
if ('d' == outData[readPoint])
{
int* variableInts = va_arg(variables, int*);
int variableSize = va_arg(variables, int);
for (register int i = 0; i < variableSize; ++i)
{
if (0 != i)
fputs(", ", stdout);
PrintNumber(0, variableInts[i], 0);
}
}
else if ('f' == outData[readPoint])
{
double* variableDoubles = va_arg(variables, double*);
int variableSize = va_arg(variables, int);
for (register int i = 0; i < variableSize; ++i)
{
if (0 != i)
fputs(", ", stdout);
PrintNumber(0, (int)variableDoubles[i] / 1 , variableDoubles[i] - (int)variableDoubles[i]);
}
}
else if ('s' == outData[readPoint])
{
const char** variableStrings = va_arg(variables, const char**);
int variableSize = va_arg(variables, int);
for (register int i = 0; i < variableSize; ++i)
{
if (0 != i)
fputs(", ", stdout);
fputs(variableStrings[i], stdout);
}
}
fputchar('}');
}
else
{
fputchar(outData[readPoint]);
}
}
va_end(variables);
}
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 aa[3] = { 1, 2, 3 };
char *bb[2] = { "abc", "def" };
print("array: @d\n", aa, 3);
print("array: @s\n", bb, 2);
int aaa = 123;
int bbb = 12345;
int ccc = 12345678;
print("number: %5d\n", aaa);
print("number: %5d\n", bbb);
print("number: %5d\n", ccc);
}