利用可变参数模拟实现printf打印

 //函数原型: 

//print(char *format, ...)

#include <stdio.h> 
#include <stdarg.h> 
#include <assert.h> 
int myprintf(const char *format, ...) 
{ 
	va_list arg; 
	assert(format); 

	va_start(arg, format); 
	while (*format) 
	{ 
		if (*format == '%') 
		{ 
			format++; 
			switch (*format) 
			{ 
			case's': 
				{ 
					char *s = va_arg(arg,char*); 
					while (*s) 
					{ 
						puts(s); 
					} 
				} 
				break; 
			case'c': 
				{ 
					char c = va_arg(arg, char); 
					putchar(c); 
				} 
				break; 
			case'%': 
				{ 
					putchar('%'); 
				} 
				break; 
			default: 
				puts("format error!\n"); 
				return 0; 
			} 
		} 
		else if (*format == '\\') 
		{ 
		} 
		else 
		{ 
			putchar(*format); 
		} 
		format++; 
	} 
	va_end(arg); 
	return 0; 
} 
int main() 
{ 
	char c = 'c'; 
	char *s = "hello word"; 
	int a = 100;
	myprintf("hello %c,hello, %s,%d\n", c, s,a); 
	myprintf("%s %c%c%c %d\n","hello",'b','i','t',100);
	system("pause"); 
	return 0; 
} 

猜你喜欢

转载自blog.csdn.net/qq_39478237/article/details/80637176