Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Скачиваний:
16
Добавлен:
01.05.2014
Размер:
2.19 Кб
Скачать
#include <iostream.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <floatingpoint.h>

#define SHOW(s) fputs(s,stdout), cnt+=strlen(s)

/* my version of printf */
int my_printf ( const char* format, ...) 
{
	char *tokp, ifmt[256], *hdr = ifmt, buf[256];
        int  cnt = 0;
	va_list pa;
    
        strcpy(ifmt,format);
	va_start(pa,format);

	/* search for the '%' key character */
	while (tokp=strchr(hdr,'%')) {
		*tokp++ = '\0';
		SHOW(hdr);                      	// show leading text string up to '%'
		if (strchr("dfgeisc%",*tokp)) {		// do if next char is a legal format spec
			switch (*tokp) {
				case 'd':		// %i, %d
				case 'i':
                                        gconvert((double)va_arg(pa,int),sizeof(buf),0,buf);
					break;
				case 's':		// %s
					strcpy(buf,va_arg(pa,char*));
					break;
				case 'c':		// %c
					buf[0] = va_arg(pa,char);
					buf[1] = '\0';
					break;
				case 'f':		// %f
                                        gconvert(va_arg(pa,double),8,1,buf);
					break;
				case 'g':		// %g
                                        gconvert(va_arg(pa,double),8,0,buf);
					break;
				case '%':		// %%
                                        strcpy(buf,"%");
					break;
			}
			SHOW(buf);			// show the extracted argument
		}
		else {	// not a format spec. Show the char. as is
			putchar(*tokp);
			cnt++;
		}
		hdr = tokp + 1;
	}
	SHOW(hdr); 	// show the last trailing text, if any
	va_end(pa);
	return cnt;	// return the no. of characters printed
}

int main()
{
	int cnt = my_printf("Hello %% %s %zZZ\n", "world");
	cout << "No. char.: " << cnt << endl;
	cnt = printf("Hello %% %s %zZZ\n", "world");
	cout << "No. char.: " << cnt << endl << endl;
	cnt = my_printf("There are %d days in %c year\n", 365, 'A');
	cout << "No. char.: " << cnt << endl;
	cnt = printf("There are %d days in %c year\n", 365, 'A');
	cout << "No. char.: " << cnt << endl << endl;
	cnt = my_printf("%g x %i = %f\n", 8.8, 8, 8.8*8);
	cout << "No. char.: " << cnt << endl;
	cnt = printf("%g x %i = %f\n", 8.8, 8, 8.8*8);
	cout << "No. char.: " << cnt << endl << endl;
	return 0;
}
Соседние файлы в папке ch4