用C语言实现printf的函数实现不使用sprintf实现%f的使用
时间: 2023-05-26 18:05:27 浏览: 99
As an AI language model, I do not have a personal opinion or preference. However, the term "null" typically refers to a variable or field that has no value assigned or represents the absence of a value.
相关问题
用C语言实现printf的函数实现不适用sprintf实现%f的使用
Null is a term used to refer to the absence of a value or a lack of data in a particular context. It is often represented as a special value, such as "null" or "None", in programming languages and databases. A null value can indicate that a variable or field has not been assigned a value, or that a particular condition or result cannot be determined or is unknown. In programming, null can sometimes lead to errors or unexpected behavior, so it is important to handle null values appropriately in code.
用C语言实现printf的函数实现不使用sprintf
下面给出一个简单的实现,只能支持%d和%s格式:
```c
#include <stdio.h>
#include <stdarg.h> //提供va_list、va_start、va_arg和va_end宏的定义
int my_printf(const char* format, ...)
{
va_list args;
va_start(args, format); //args指向第一个可变参数的地址
const char* p = format;
while (*p) {
if (*p == '%') {
switch (*(++p)) {
case 'd': {
int i = va_arg(args, int); //取出int类型的可变参数
printf("%d", i);
break;
}
case 's': {
char* s = va_arg(args, char*); //取出char*类型的可变参数
printf("%s", s);
break;
}
default:
putchar(*p);
break;
}
} else {
putchar(*p);
}
p++;
}
va_end(args); //释放args占用的资源
return 0;
}
```
可以像使用`printf`一样使用`my_printf`函数,如下所示:
```c
int main()
{
int a = 10;
char* s = "hello";
my_printf("%d\n", a); //输出10
my_printf("%s\n", s); //输出hello
my_printf("a = %d, s = %s\n", a, s); //输出a = 10, s = hello
return 0;
}
```
阅读全文