Program:
#ifndef PRINTF_H
#define PRINTF_H
#include "my_put_char.h"
int my_printf(char *str, ...);
#endif
This is my Header file for my function.
#include <stdio.h>
#include "my_put_char.h"
void my_put_char(char c)
{
fwrite(&c, sizeof(char), 1, stdout);
}
This is my putchar implementation(my_put_char.c).
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "printf.h"
int my_printf(char *str, ...)
{
if(str == NULL)
return 0;
int i;
char a;
va_list print;
va_start(print,str);
for(i = 0; str[i] ; i++)
{
if(str[i] == '%')
{
i++;
switch(str[i])
{
case 'c':
a = va_arg(print, char);
my_put_char(a);
break;
}
}
}
va_end(print);
return 0;
}
At last, this is a part of my printf implementation.
I'm testing with %c to display a character.
When I do my_print("%c", 'd'); from main.c
it compiles and displays d.
But when I do my_print("%c", "hi"); , it still compiles and displays a number.
Question:
After(or before) writing a = va_arg(print, char); Is there a way to check whether my input is a different data type?
I'm trying to display an error if my input is a different data type.
I'm on this subject for 2 days and couldn't find any answer. Thank you so much for your time!
printf.hheader includemy_put_char.hheader? Are users of yourprintf.hgoing to use what's declared in it? Note that the format string should beconst char *fmt(with the addedconst); C99, C11 and POSIX would have it qualified withrestricttoo (int printf(const char * restrict format, ...);). Your implementation file should include yourmy_put_char.hheader; it calls the function. Your other header should (probably) not include it.va_arg, you must specify a promoted type —intorunsigned intordoubleand not anything shorter (char,short,float, etc). Your linea = va_arg(print, char);is immediately invoking undefined behaviour. (The verbiage from the standard §7.16.1.1 is: …or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the behavior is undefined, except… and the exceptions don't apply here (they relate to signed vs unsigned integers andvoid *vschar *).__attribute__((format(printf,1,2))notation for checkingprintf()-like functions — it's hard to do it otherwise.